package com.cloud.phone.task.tiktok;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.accessibility.AccessibilityNodeInfo;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.cloud.phone.R;
import com.cloud.phone.base.BaseApp;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.task.BaseDealTools;
import com.cloud.phone.task.BaseTask;
import com.cloud.phone.task.MsgTaskManger;
import com.cloud.phone.task.TaskManager;
import com.cloud.phone.task.bean.AccountsListObject;
import com.cloud.phone.task.bean.ChatMsgList;
import com.cloud.phone.task.bean.MsgTaskBean;
import com.cloud.phone.task.bean.PersonInfo;
import com.cloud.phone.task.bean.RecognizeInfo;
import com.cloud.phone.task.bean.ServerInnerDataBean;
import com.cloud.phone.task.bean.UserInfo;
import com.cloud.phone.task.taskCongfig.FindIdResouresConfig;
import com.cloud.phone.task.taskCongfig.TaskTypeConfig;
import com.cloud.phone.tools.AccessibilityTool;
import com.cloud.phone.tools.LogUtils;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.utils.BingTopDama;
import com.cloud.phone.utils.ImageCropper;
import com.cloud.phone.utils.MediaRefreshHelper;
import com.cloud.phone.view.TsUtils;
import com.cloud.phone.websocket.WebsocketUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TickTokTaskDealTools extends BaseDealTools {
    public TikTokTask tikTokTask;
    private int maxVerifyCodeTryTime=5;

    public TickTokTaskDealTools(TikTokTask tikTokTask) {
        super(tikTokTask);
        this.tikTokTask = tikTokTask;
        service = tikTokTask.service;
    }


    /**
     * 检测是否登录
     *
     * @param onGetLoginStatus
     */
    public void checkIsLogin(TikTokTask.OnGetLoginStatus onGetLoginStatus) throws InterruptedException {
        if (checkCurrentPageIsMainPage()) {
            LogUtils.i("当前在主页面");
            AccessibilityNodeInfo nodeInfo = findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
            if (nodeInfo != null) {
                click(nodeInfo);
                LogUtils.i("已进入个人中心页面");
                Thread.sleep(3000);
                if (checkIsInPersonalPage()) {
                    LogUtils.w("到了个人中心页面且已经登录成功");
                    tikTokTask.showLogAndTsPrint("登录状态：" + "已登录成功");
                    if (onGetLoginStatus != null) {
                        onGetLoginStatus.onGetLoginStatus(true);
                    }
                    Thread.sleep(3000);
                    tikTokTask.onTaskFinish();
                } else {
                    AccessibilityNodeInfo noLoginNode = findNodeFirstById(FindIdResouresConfig.notLoginHasNoAccountId);
                    if (noLoginNode != null) {
                        tikTokTask.showLogAndTsPrint("登录状态：" + "未登录");
                        if (onGetLoginStatus != null) {
                            onGetLoginStatus.onGetLoginStatus(false);
                        }
                        Thread.sleep(3000);
                        tikTokTask.onTaskFinish();
                    } else {
                        tikTokTask.changeTaskStatusToStart();
                    }
                }
            } else {
                tikTokTask.changeTaskStatusToStart();
            }
        } else {
            backToTiktokMainPage();
        }
    }


    /**
     * 通过判断主页面顶部的tab个数确定登录态（2个tab的情况为未登录，超过的情况下为登录成功）
     *
     * @return
     */
    private boolean checkMainPageTabSize() {
        List<AccessibilityNodeInfo> nodeInfos = findNodeInfoByClassName(getRootNodeInfo(), FindIdResouresConfig.topTabClassName);
        if (MyUtils.isEmpty(nodeInfos) || nodeInfos.size() <= 2) {
            return false;
        } else {
            return true;
        }
    }


    public void closeCenterTipsDialog() {
        //判断并关闭自定义弹框
        closeCustomTipDialog();
        //关闭关注的弹框
        closeAttentionTipDialog();
    }


    /**
     * 判断当前页面是否为tiktok的首页
     *
     * @return
     */
    public boolean checkCurrentPageIsMainPage() throws InterruptedException {
        closeDialogAndSwipe();
        //关闭自定义弹框
        AccessibilityNodeInfo nodeInfo = findNodeFirstById(FindIdResouresConfig.mainBottomBtId);
        AccessibilityNodeInfo nodeInfo2 = findNodeFirstById(FindIdResouresConfig.mainTopBarLinearId);
        AccessibilityNodeInfo nodeInfo3 = findNodeFirstById(FindIdResouresConfig.mainTopBarItemTextId);
        if (nodeInfo != null && nodeInfo.isSelected()) {
            LogUtils.i("已进入tiktok首页");
            tikTokTask.showLogAndTsPrint("已在tiktok首页");
            return true;
        } else if (nodeInfo2 != null && nodeInfo3 != null) {
            LogUtils.i("已进入tiktok首页");
            tikTokTask.showLogAndTsPrint("已在tiktok首页");
            return true;
        }
        if(!MyUtils.isEmpty(getCurrentPagePackageName())){
            if(!getCurrentPagePackageName().equals(Constants.tiktokPackageName)){
                AppUtils.launchApp(Constants.tiktokPackageName);
                Thread.sleep(2000);
            }
        }
        return false;
    }

    public void closeDialogAndSwipe()throws InterruptedException{
        Thread.sleep(2000);
        //关闭首次的弹框
        closeFirstEnterInTikTok();
        //关闭中间弹窗
        closeCenterTipsDialog();
        //检测是否存在权限允许弹框
        allowSystemPermission();
        AccessibilityNodeInfo nodeInfo = findNodeFirstById(FindIdResouresConfig.mainBottomBtId);
        AccessibilityNodeInfo jumpBt = findNodeFirstById(FindIdResouresConfig.register_jump_bt_id);
        if(jumpBt!=null&&nodeInfo==null){
            clickXy(jumpBt);
            Thread.sleep(2000);
        }
        AccessibilityNodeInfo chooseMusicNextBtNode = findNodeFirstById(FindIdResouresConfig.publishAcChooseMusicNextId);
        AccessibilityNodeInfo publishAcTopBackNode = findNodeFirstById(FindIdResouresConfig.publishAcTopBackId);
        if(chooseMusicNextBtNode!=null&&publishAcTopBackNode!=null){
            tikTokTask.showLogAndTsPrint("在发布作品页面");
            clickXy(publishAcTopBackNode);
            Thread.sleep(2000);
            Rect rect = new Rect();
            publishAcTopBackNode.getBoundsInScreen(rect);
            float left = rect.left;
            float right = rect.right;
            float top = rect.top;
            float bottom = rect.bottom;
            int x = (int) ((left + right) / 2);
            int y = (int) ((top + bottom) / 2);
            if(y<0){
                y= (int) (Math.abs(top-bottom)*2);
            }
            AccessibilityTool.getInstance().clickScreen(service, (int) right, (int) (bottom+rect.height()/2));
            tikTokTask.showLogAndTsPrint("放弃上次的发布操作");
            Thread.sleep(2000);
        }
    }

    private void closeFirstEnterInTikTok() throws InterruptedException {
        AccessibilityNodeInfo firstCenterId = findNodeFirstById(FindIdResouresConfig.close_center_first_inner_dialog_sure_bt);
        List<AccessibilityNodeInfo> closeAgreeDialogBt = findNodesByText("同意并继续");
        if(isNodeExist(closeAgreeDialogBt)){
            clickXy(closeAgreeDialogBt.get(0));
            tikTokTask.showLogAndTsPrint("同意并继续");
            Thread.sleep(3000);
        }
        if(firstCenterId!=null){
            tikTokTask.showLogAndTsPrint("关闭中间弹框第一次");
            while (firstCenterId!=null) {
                clickXy(firstCenterId);
                firstCenterId = findNodeFirstById(FindIdResouresConfig.close_center_first_inner_dialog_sure_bt);
                Thread.sleep(2000);
            }
            Thread.sleep(2000);
            tikTokTask.showLogAndTsPrint("等待出第二次弹框");
            Thread.sleep(6000);
        }
        if(closeCustomTipDialog()) {
            Thread.sleep(3000);
        }
//        AccessibilityNodeInfo swipeNodeImageNode =findNodeFirstById(FindIdResouresConfig.swipe_center_tips_node_id);
//        AccessibilityNodeInfo swipeNodeImageNode2 =findNodeFirstById(FindIdResouresConfig.swipe_center_tips_node_id2);
//        if(swipeNodeImageNode!=null||swipeNodeImageNode2!=null){
//            swipeYearScrollBarToBottom(1);
//        }
        List<AccessibilityNodeInfo> nodes = AccessibilityTool.getInstance().findNodesByText(null, null, service, "上滑查看更多视频");
        if(isNodeExist(nodes)){
            swipeYearScrollBarToBottom(1);
        }
    }

    private void allowSystemPermission() throws InterruptedException {
        AccessibilityNodeInfo allowBtNode1 = findNodeFirstById(FindIdResouresConfig.allow_permission_button1);
        AccessibilityNodeInfo allowBtNode2 = findNodeFirstById(FindIdResouresConfig.allow_permission_button2);
        if(allowBtNode1!=null){
            clickXy(allowBtNode1);
            tikTokTask.showLogAndTsPrint("允许权限");
            Thread.sleep(3000);
        }
        if(allowBtNode2!=null){
            clickXy(allowBtNode2);
            tikTokTask.showLogAndTsPrint("允许权限");
            Thread.sleep(3000);
        }
    }


    public void allowPermission() throws InterruptedException {
        AccessibilityNodeInfo allowBtNode1 = findNodeFirstById(FindIdResouresConfig.allow_permission_button1);
        AccessibilityNodeInfo allowBtNode2 = findNodeFirstById(FindIdResouresConfig.allow_permission_button2);
        if(allowBtNode1!=null){
            clickXy(allowBtNode1);
            tikTokTask.showLogAndTsPrint("允许权限");
            Thread.sleep(3000);
        }
        if(allowBtNode2!=null){
            clickXy(allowBtNode2);
            tikTokTask.showLogAndTsPrint("允许权限");
            Thread.sleep(3000);
        }
    }





    /**
     * 判断当前页面是否为tiktok的收件箱（对话消息页面）
     *
     * @return
     */
    public boolean checkCurrentPageIsMessageBoxPage() throws InterruptedException {
        Thread.sleep(2000);
        //判断并关闭自定义弹框
        boolean isCloseCustomDialog = closeCustomTipDialog();
        //判断关闭关注的弹框
        boolean isCloseAttentionDialog = closeAttentionTipDialog();
        if (isCloseAttentionDialog || isCloseCustomDialog) {
            return checkCurrentPageIsMessageBoxPage();
        }
        //关闭自定义弹框
        AccessibilityNodeInfo nodeInfo = findNodeFirstById(FindIdResouresConfig.messageBoxBottomBtId);
        if (nodeInfo != null) {
            clickXy(nodeInfo);
            Thread.sleep(3000);
            swipeToTop(3);
            Thread.sleep(2000);
            AccessibilityNodeInfo newFanItemBtNode = findNodeFirstById(FindIdResouresConfig.messageBoxNewFanBtId);
            if (newFanItemBtNode != null) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取登录状态下用户的个人资料
     */
    public void getUserInfo(OnUserInfoGetListener onUserInfoGetListener, String accountWithUserName) throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        //检测是否在个人中心页面
        if (checkIsInPersonalPage()) {
            Thread.sleep(1000);
            getInfo(onUserInfoGetListener, accountWithUserName);
        } else {
            //不在个人中心页面，准备进入个人中心页面
            if (checkCurrentPageIsMainPage()) {
                LogUtils.w("回到首页成功");
//                boolean isLogin = checkMainPageTabSize();
                AccessibilityNodeInfo nodes = findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
                if (nodes != null) {
                    clickXy(nodes);
                } else {
                    tikTokTask.showLogAndTsPrint("未找到底部主页按钮");
                }
                Thread.sleep(3000);
                tikTokTask.changeTaskStatusToStart();
            } else {
                List<AccessibilityNodeInfo> itemNodes = findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                AccessibilityNodeInfo bottomChangeNode = findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                if (isNodeExist(itemNodes) && bottomChangeNode != null) {
                    tikTokTask.onTaskErr("账号未登录");
                    if(onUserInfoGetListener!=null){
                        onUserInfoGetListener.onUserInfoGet(null);
                    }
                    return;
                }

                List<AccessibilityNodeInfo> tagNodes = findNodesById(FindIdResouresConfig.register_select_tag_node_id);
                AccessibilityNodeInfo nextBtNode = findNodeFirstById(FindIdResouresConfig.register_select_tag_next_bt_node_id);
                if(isNodeExist(tagNodes)&&tagNodes.size()>=2&&nextBtNode!=null){
                    tikTokTask.onTaskErr("账号未注册");
                    if(onUserInfoGetListener!=null){
                        onUserInfoGetListener.onUserInfoGet(null);
                    }
                    return;
                }
                AccessibilityNodeInfo birthYearNode = findNodeFirstById(FindIdResouresConfig.register_birthday_year_scroll1NodeId);
                AccessibilityNodeInfo birthMonthNode = findNodeFirstById(FindIdResouresConfig.register_birthday_month_scroll1NodeId);
                AccessibilityNodeInfo birthDayNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_scroll1NodeId);
                AccessibilityNodeInfo nextRegisterBtNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_next_bt_NodeId);
                if(birthYearNode!=null&&birthMonthNode!=null&&birthDayNode!=null&&nextRegisterBtNode!=null){
                    tikTokTask.onTaskErr("账号未注册");
                    if(onUserInfoGetListener!=null){
                        onUserInfoGetListener.onUserInfoGet(null);
                    }
                    return;
                }
                tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
                backOnce();
                Thread.sleep(2000);
                tikTokTask.changeTaskStatusToStart();
            }
        }
    }


    public boolean isForceStop;
    public void forceStop() {
        this.isForceStop=true;
    }


    public interface OnUserInfoGetListener {
        void onUserInfoGet(UserInfo userInfo) throws InterruptedException;
    }


    public interface OnVerifyCodeGetListener {
        void onVerifyCodeGet(String verifyCode) throws InterruptedException;
    }


    /**
     * 抓取当前页面的用户资料
     */
    private void getInfo(OnUserInfoGetListener onUserInfoGetListener, String accountWithUserName) throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        String userName = "";
        String nickName = "";
        String fanCount = "";
        String signText = "";
        String attentionCount = "";
        String likeCount = "";
        //获取头像
//        getUserHeadImage();
        //获取昵称
        nickName = getNickName();
        //获取用户名
        userName = getUserName();
        //获取粉丝数
        fanCount = getUserFanCount();
        //获取关注数
        attentionCount = getUserAttentionCount();
        //获取点赞数
        likeCount = getUserLikeCount();
        //获取用户签名
        signText = getSignText();
        LogUtils.i("获取到个人信息数据：\n" + "用户名：" + userName + "\n昵称：" + nickName + "\n粉丝数：" + fanCount + "\n关注数：" + attentionCount + "\n点赞数：" + likeCount + "\n签名：" + signText);
        tikTokTask.showLogAndTsPrint("当前用户：" + userName + " 粉丝:" + fanCount + " 关注:" + attentionCount + " 点赞:" + likeCount);
        if (!MyUtils.isEmpty(userName)) {
            if (onUserInfoGetListener != null) {
                UserInfo userInfo = new UserInfo();
                userInfo.setAttention(attentionCount);
                userInfo.setFans(fanCount);
                userInfo.setLike(likeCount);
                userInfo.setAccount(userName);
                userInfo.setNickName(nickName);
                TaskManager.getInstance().currentTiktokUserInfo = userInfo;
                if (accountWithUserName != null) {
                    if (accountWithUserName.equals(userName)) {
                        AccessibilityNodeInfo changeBtId = findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
                        if (changeBtId != null) {
                            try {
                                tikTokTask.showLogAndTsPrint("点击切换账号按钮");
                                if(Constants.isServiceApplication) {
                                    AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                                    Thread.sleep(2000);
                                    List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                                    if(!isNodeExist(accountsNode)){
                                        clickXy(changeBtId);
                                        Thread.sleep(2000);
                                    }
                                }else{
                                    clickXy(changeBtId);
                                    Thread.sleep(3000);
                                }
                                List<String> accountList = new ArrayList<>();
                                for(int swipeTime=0;swipeTime<2;swipeTime++) {
                                    List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                                    if (isNodeExist(accountsNode)) {
                                        String lastText=accountsNode.get(accountsNode.size()-1).getText().toString();
                                        int maxFor=accountsNode.size();
                                        if("添加账号".equals(lastText)){
                                            maxFor=accountsNode.size()-1;
                                        }
                                        for (int i = 0; i < maxFor; i++) {
                                            String account = accountsNode.get(i).getText().toString();
                                            if (account.startsWith("@")) {
                                                account = account.substring(1);
                                            }
                                            boolean isAccountHasInList=false;
                                            for(String accInList:accountList){
                                                if(accInList.equals(account)){
                                                    isAccountHasInList=true;
                                                    break;
                                                }
                                            }
                                            if (!MyUtils.isEmpty(account)&&!isAccountHasInList) {
                                                accountList.add(account);
                                            }
                                        }
                                        if (!accountList.isEmpty()) {
                                            userInfo.setAccountList(accountList);
                                        }
                                    }
                                    if(accountList.size()>=4){
                                        swipe(ScreenUtils.getAppScreenWidth()/2,1212,ScreenUtils.getAppScreenWidth()/2,880,600);
                                    }
                                }
                                if (MyUtils.isEmpty(accountList)) {
                                    accountList.add(userInfo.getAccount());
                                }
                                tikTokTask.showLogAndTsPrint("获取账号列表成功");
                                Thread.sleep(3000);
                                TaskManager.getInstance().currentTiktokUserInfo = userInfo;
                                tikTokTask.createCurrentUpdateInfo(userInfo,2,true);
                                tikTokTask.sendMsgToServer();
                                onUserInfoGetListener.onUserInfoGet(userInfo);
                            } catch (InterruptedException e) {
                                onUserInfoGetListener.onUserInfoGet(userInfo);
                            }
                        }else {
                            onUserInfoGetListener.onUserInfoGet(userInfo);
                        }
                    } else {
                        //不一致，准备切换账号
                        AccessibilityNodeInfo changeBtId = findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
                        if (changeBtId != null) {
//                            clickXy(changeBtId);
                            if(Constants.isServiceApplication) {
                                AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                                Thread.sleep(2000);
                                List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                                if(!isNodeExist(accountsNode)){
                                    clickXy(changeBtId);
                                    Thread.sleep(2000);
                                }
                            }else{
                                clickXy(changeBtId);
                                Thread.sleep(3000);
                            }
                            List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                            AccessibilityNodeInfo accountNode = null;
                            if (isNodeExist(accountsNode)) {
                                for(int swipe=0;swipe<2;swipe++) {
                                    String lastText=accountsNode.get(accountsNode.size()-1).getText().toString();
                                    int maxFor=accountsNode.size();
                                    if("添加账号".equals(lastText)){
                                        maxFor=accountsNode.size()-1;
                                    }
                                    for (int i = 0; i < maxFor; i++) {
                                        String account = accountsNode.get(i).getText().toString();
                                        if (account.startsWith("@")) {
                                            account = account.substring(1);
                                        }
                                        if (accountWithUserName.equals(account)) {
                                            accountNode = accountsNode.get(i);
                                            break;
                                        }
                                    }
                                    swipe(ScreenUtils.getAppScreenWidth()/2,1212,ScreenUtils.getAppScreenWidth()/2,880,600);
                                }
                                if (accountNode != null) {
                                    clickXy(accountNode);
                                    Thread.sleep(10000);
                                    AccessibilityNodeInfo dialogNode = findNodeFirstById(FindIdResouresConfig.dialogMiddleNodeId);
                                    if (dialogNode != null && FindIdResouresConfig.dialogViewGroupNodeId.equals(dialogNode.getParent().getViewIdResourceName())) {
                                        onUserInfoGetListener.onUserInfoGet(null);
                                        return;
                                    }
                                    getUserInfo(onUserInfoGetListener, accountWithUserName);
                                } else {
                                    tikTokTask.onTaskErr("未登录账号:"+accountWithUserName);
                                    onUserInfoGetListener.onUserInfoGet(null);
                                }
                            } else {
                                onUserInfoGetListener.onUserInfoGet(null);
                            }
                        } else {
                            tikTokTask.changeTaskStatusToStart();
                        }
                    }
                } else {
                    //执行定时更新数据的任务
                    AccessibilityNodeInfo changeBtId = findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
                    if (changeBtId != null) {
                        try {
                            tikTokTask.showLogAndTsPrint("点击切换账号按钮");
//                            clickXy(changeBtId);
                            if(Constants.isServiceApplication) {
                                AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                                Thread.sleep(2000);
                                List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                                if(!isNodeExist(accountsNode)){
                                    clickXy(changeBtId);
                                    Thread.sleep(2000);
                                }
                            }else{
                                clickXy(changeBtId);
                                Thread.sleep(3000);
                            }
                            List<String> accountList = new ArrayList<>();
                            for(int swipeTime=0;swipeTime<2;swipeTime++) {
                                List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                                if (isNodeExist(accountsNode)) {
                                    String lastText=accountsNode.get(accountsNode.size()-1).getText().toString();
                                    int maxFor=accountsNode.size();
                                    if("添加账号".equals(lastText)){
                                        maxFor=accountsNode.size()-1;
                                    }
                                    for (int i = 0; i < maxFor; i++) {
                                        String account = accountsNode.get(i).getText().toString();
                                        if (account.startsWith("@")) {
                                            account = account.substring(1);
                                        }
                                        boolean isAccountHasInList=false;
                                        for(String accInList:accountList){
                                            if(accInList.equals(account)){
                                                isAccountHasInList=true;
                                                break;
                                            }
                                        }
                                        if (!MyUtils.isEmpty(account)&&!isAccountHasInList) {
                                            accountList.add(account);
                                        }
                                    }
                                    if (!accountList.isEmpty()) {
                                        userInfo.setAccountList(accountList);
                                    }
                                }
                                if(accountList.size()>=4){
                                    swipe(ScreenUtils.getAppScreenWidth()/2,1212,ScreenUtils.getAppScreenWidth()/2,880,600);
                                }
                            }
                            if (MyUtils.isEmpty(accountList)) {
                                accountList.add(userInfo.getAccount());
                            }
                            tikTokTask.showLogAndTsPrint("获取账号列表成功");
                            Thread.sleep(3000);
                            onUserInfoGetListener.onUserInfoGet(userInfo);
                        } catch (InterruptedException e) {
                            onUserInfoGetListener.onUserInfoGet(null);
                        }
                    } else {
                        tikTokTask.showLogAndTsPrint("未找到切换账号按钮，待重试");
                        Thread.sleep(3000);
                        backOnce();
                        tikTokTask.changeTaskStatusToStart();
                    }
                }
            } else {
                UserInfo userInfo = new UserInfo();
                userInfo.setAttention(attentionCount);
                userInfo.setFans(fanCount);
                userInfo.setLike(likeCount);
                userInfo.setAccount(userName);
                userInfo.setNickName(nickName);
                AccessibilityNodeInfo changeBtId = findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
                if (changeBtId != null) {
                    try {
                        tikTokTask.showLogAndTsPrint("点击切换账号按钮");
                        if(Constants.isServiceApplication) {
                            AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                            Thread.sleep(2000);
                            List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                            if(!isNodeExist(accountsNode)){
                                clickXy(changeBtId);
                                Thread.sleep(2000);
                            }
                        }else{
                            clickXy(changeBtId);
                            Thread.sleep(3000);
                        }
                        List<String> accountList = new ArrayList<>();
                        for(int swipeTime=0;swipeTime<2;swipeTime++) {
                            List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                            if (isNodeExist(accountsNode)) {
                                String lastText=accountsNode.get(accountsNode.size()-1).getText().toString();
                                int maxFor=accountsNode.size();
                                if("添加账号".equals(lastText)){
                                    maxFor=accountsNode.size()-1;
                                }
                                for (int i = 0; i < maxFor; i++) {
                                    String account = accountsNode.get(i).getText().toString();
                                    if (account.startsWith("@")) {
                                        account = account.substring(1);
                                    }
                                    boolean isAccountHasInList=false;
                                    for(String accInList:accountList){
                                        if(accInList.equals(account)){
                                            isAccountHasInList=true;
                                            break;
                                        }
                                    }
                                    if (!MyUtils.isEmpty(account)&&!isAccountHasInList) {
                                        accountList.add(account);
                                    }
                                }
                                if (!accountList.isEmpty()) {
                                    userInfo.setAccountList(accountList);
                                }
                            }
                            if(accountList.size()>=4){
                                swipe(ScreenUtils.getAppScreenWidth()/2,1212,ScreenUtils.getAppScreenWidth()/2,880,600);
                            }
                        }
                        if (MyUtils.isEmpty(accountList)) {
                            accountList.add(userInfo.getAccount());
                        }
                        tikTokTask.showLogAndTsPrint("获取账号列表成功");
                        Thread.sleep(3000);
                        TaskManager.getInstance().currentTiktokUserInfo = userInfo;
                        //更新用户数据（非定时更新）
                        tikTokTask.createCurrentUpdateInfo(userInfo,2,true);
                        tikTokTask.sendMsgToServer();
                        tikTokTask.onTaskFinish();
                    } catch (InterruptedException e) {
                        tikTokTask.onTaskErr();
                    }
                }else {
                    tikTokTask.onTaskFinish();
                }
            }
        } else {
            if (onUserInfoGetListener != null) {
                tikTokTask.showLogAndTsPrint("无法获取用户信息");
                Thread.sleep(2000);
                onUserInfoGetListener.onUserInfoGet(null);
            } else {
                tikTokTask.onTaskErr("无法获取用户信息");
                //更新用户数据（非定时更新）
                tikTokTask.createCurrentUpdateInfo(null,2,true);
                tikTokTask.sendMsgToServer();
            }
        }
    }

    private String getSignText() {
        List<AccessibilityNodeInfo> tabHostRootNode = findNodesById(FindIdResouresConfig.personalUserInfoRootId);
        try {
            if (isNodeExist(tabHostRootNode)) {
                if (tabHostRootNode.get(0) != null && tabHostRootNode.get(0).getChildCount() < 11) {
                    LogUtils.d("签名获取失败");
                } else {
                    if (tabHostRootNode.get(0) != null && tabHostRootNode.get(0).getChild(11) == null) {
                        LogUtils.d("签名获取失败");
                        return "";
                    }
                    AccessibilityNodeInfo signTextView = tabHostRootNode.get(0).getChild(11);
                    if (signTextView == null || signTextView.getChild(0) == null) {
                        return "";
                    }
                    if (signTextView.getChild(0).getText() == null) {
                        return "";
                    }
                    String signText = signTextView.getChild(0).getText().toString();
                    LogUtils.d("签名获取成功：" + signText);
                    return signText;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.d("签名获取失败");
        return "";
    }


    /**
     * 获取用户粉丝数量
     *
     * @return
     */
    private String getUserFanCount() {
        List<AccessibilityNodeInfo> fanceRootView = findNodesById(FindIdResouresConfig.personalFanCountId);
        if (isNodeExist(fanceRootView)) {
            if (fanceRootView.get(0) == null) {
                LogUtils.d("粉丝获取失败");
            } else {
                String fanCount = fanceRootView.get(0).getText().toString();
                LogUtils.d("粉丝数获取成功：" + fanCount);
                return fanCount;
            }
        } else {
            LogUtils.d("粉丝数获取失败");
        }
        return "";
    }


    /**
     * 获取用户关注数量
     *
     * @return
     */
    private String getUserAttentionCount() {
        List<AccessibilityNodeInfo> attentionAndLikeCountRootView = findNodesById(FindIdResouresConfig.personalAttentionAndLikeCountId);
        if (isNodeExist(attentionAndLikeCountRootView)) {
            if (attentionAndLikeCountRootView.size() < 2) {
                LogUtils.d("关注数获取失败");
            } else {
                if (attentionAndLikeCountRootView.get(0) == null) {
                    LogUtils.d("关注数获取失败");
                    return "";
                }
                String fanCount = attentionAndLikeCountRootView.get(0).getText().toString();
                LogUtils.d("关注数获取成功：" + fanCount);
                return fanCount;
            }
        } else {
            LogUtils.d("关注数获取失败");
        }
        return "";
    }


    private String getUserLikeCount() {
        List<AccessibilityNodeInfo> attentionAndLikeCountRootView = findNodesById(FindIdResouresConfig.personalAttentionAndLikeCountId);
        if (isNodeExist(attentionAndLikeCountRootView)) {
            if (attentionAndLikeCountRootView.size() < 2) {
                LogUtils.d("点赞数获取失败");
            } else {
                if (attentionAndLikeCountRootView.get(1) == null) {
                    LogUtils.d("点赞数获取失败");
                    return "";
                }
                String likeCount = attentionAndLikeCountRootView.get(1).getText().toString();
                LogUtils.d("点赞数获取成功：" + likeCount);
                return likeCount;
            }
        } else {
            LogUtils.d("点赞数获取失败");
        }
        return "";
    }


    /**
     * 获取用户头像截图
     *
     * @return
     */
    private Bitmap getUserHeadImage() {
        List<AccessibilityNodeInfo> nodes = findNodesById(FindIdResouresConfig.personalImageHeadId);
        if (isNodeExist(nodes)) {
            AccessibilityNodeInfo imageView = nodes.get(0).getChild(0);
            if (imageView != null) {
                LogUtils.d("头像获取成功");
                Rect rect = new Rect();
                imageView.getBoundsInScreen(rect);
                try {
                    captureScreen();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                LogUtils.d("头像获取失败");
            }
        } else {
            LogUtils.d("头像获取失败");
        }
        return null;
    }

    /**
     * 获取用户名
     */
    private String getUserName() {
        AccessibilityNodeInfo tabHostRootNode2 = findNodeFirstById(FindIdResouresConfig.personalUserInfoRoot2Id);
        if (tabHostRootNode2 != null) {
            MsgTaskManger.showLog("获取用户名开始11");
            if (tabHostRootNode2.getChildCount() > 3) {
            MsgTaskManger.showLog("获取用户名开始22");
                if (tabHostRootNode2.getChild(1) != null) {
                    MsgTaskManger.showLog("获取用户名开始44");
                    AccessibilityNodeInfo childNode1 = tabHostRootNode2.getChild(1);
                    MsgTaskManger.showLog("获取用户名开始33");
                    while (childNode1 != null && childNode1.getChildCount() > 0) {
                        childNode1 = childNode1.getChild(0);
                    }
                    MsgTaskManger.showLog("获取用户名结束");
                    String userName="";
                    if(childNode1!=null&&childNode1.getText()!=null){
                         userName = childNode1.getText().toString();
                    }
                    LogUtils.d("用户名获取成功：" + userName);
                    if (!MyUtils.isEmpty(userName)&&userName.startsWith("@")) {
                        userName = userName.substring(1);
                    }
                    return userName;
                } else {
                    return "";
                }
            } else {
                return "";
            }
        } else {
            LogUtils.d("用户名获取失败");
        }
        return "";
    }


    /**
     * 获取用户昵称
     */
    private String getNickName() {
        List<AccessibilityNodeInfo> nodes = findNodesById(FindIdResouresConfig.personalNickNameRootId);
        if (isNodeExist(nodes)) {
            AccessibilityNodeInfo nickNameNode = nodes.get(0);
            if (nickNameNode != null) {
                String nickName = nickNameNode.getText().toString();
                LogUtils.w("昵称获取成功：" + nickName);
                return nickName;
            } else {
                LogUtils.d("昵称获取失败");
            }
        } else {
            LogUtils.d("昵称获取失败");
        }
        return "";
    }





    public void saveBitmapToInternalStorage(Bitmap bitmap, String fileName) {
        // 获取内部存储的根目录
        File directory = BaseApp.app.getFilesDir();
        // 构建文件路径
        File file = new File(directory, fileName);

        // 将Bitmap转换为字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
        byte[] bitmapBytes = bos.toByteArray();

        // 将字节数组写入文件
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapBytes);
            fos.flush();
            fos.close();
            Log.d("SaveBitmap", "Bitmap saved to internal storage");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("SaveBitmap", "Error saving bitmap to internal storage");
        }
    }


    public Bitmap captureScreen() {
        // 获取当前屏幕的根视图
        Window dialogWindow = new Dialog(BaseApp.app, R.style.ActionSheetDialogStyle).getWindow();
        View rootView = dialogWindow.getDecorView().getRootView();
        rootView.setDrawingCacheEnabled(true); // 启用DrawingCache，用于截图
        Bitmap bitmap = Bitmap.createBitmap(rootView.getWidth(), rootView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        rootView.draw(canvas); // 将视图绘制到Canvas上，生成Bitmap截图
        // 这里可以保存bitmap到文件或进行其他操作...
        return bitmap;
    }


    //判断是否在个人主页
    public boolean checkIsInPersonalPage() {
        AccessibilityNodeInfo editInfoBtNode = findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
        if (editInfoBtNode != null && editInfoBtNode.isSelected() && editInfoBtNode.isVisibleToUser()) {
            return true;
        }
        return false;
    }


    /**
     * 关键字养号任务
     *
     * @param duration         养号任务总时常
     * @param likePercent      点赞概率？%
     * @param attentionPercent 关注概率？%
     * @param commentPercent   评论概率？%
     */
    public int nextIndex = 0;

    public void searchAndAutoLookVideo(int currentKeywordsLookIndex, List<String> keyWords, long duration, int likePercent, int attentionPercent, int commentPercent) throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        int indexNow = currentKeywordsLookIndex;
        //防止因为任务重置为START后重新执行index=0覆盖关键词
        if (nextIndex != 0 && nextIndex <= keyWords.size() - 1) {
            indexNow = nextIndex;
        }
        String keyword = keyWords.get(indexNow);
        if (indexNow == 0) {
            lookedVideoSize = 0;
        }
        if (checkCurrentPageIsMainPage()) {
            //确保已经在首页了
            startDoTaskTime = System.currentTimeMillis();
            AccessibilityNodeInfo imageNode = getMainSearchIconNode();
            if (imageNode != null) {
                click(imageNode);
                Thread.sleep(2000);
                tikTokTask.showLogAndTsPrint("进入搜索页面");
                AccessibilityNodeInfo searchEtNode = findNodeFirstById(FindIdResouresConfig.searchEtId);
                if (searchEtNode != null) {
                    setNodeText(searchEtNode, keyword);
                    Thread.sleep(2000);
                    AccessibilityNodeInfo searchBtNode = findNodeFirstById(FindIdResouresConfig.searchBtId);
                    if (searchBtNode != null) {
                        clickXy(searchBtNode);
                        tikTokTask.showLogAndTsPrint("搜索关键字");
                        Thread.sleep(5000);
//                        AccessibilityNodeInfo topNode = findNodeFirstById(FindIdResouresConfig.searchTopBarId);
//                        if (topNode != null && topNode.getChildCount() > 2) {
//                            clickXy(topNode.getChild(1));
//                            tikTokTask.showLogAndTsPrint("切换到视频列表");
//                            Thread.sleep(4000);
//                            LogUtils.v("开始准备养号");
//
//                        } else {
//                            Thread.sleep(1000);
//                            tikTokTask.changeTaskStatusToStart();
//                        }
                        AccessibilityNodeInfo searchBtItemNode = findNodeFirstById(FindIdResouresConfig.searchItemBtId);
                        if (searchBtItemNode != null) {
                            clickXy(searchBtItemNode);
                            Thread.sleep(2000);
                            AccessibilityNodeInfo topSearchEtNode = findNodeFirstById(FindIdResouresConfig.searchEtTopBtId);
                            if (topSearchEtNode != null) {
                                boolean isAutoLookFinish = startLoopLookVideo(true, duration, likePercent, attentionPercent, commentPercent);
                                if (isAutoLookFinish) {
                                    if (keyWords.size() - 1 == indexNow) {
                                        //养号结束
                                        tikTokTask.showLogAndTsPrint("养号结束，共观看视频:" + lookedVideoSize + "条");
                                        tikTokTask.onTaskFinish();
                                    } else {
                                        Thread.sleep(1000);
                                        nextIndex = indexNow + 1;
                                        tikTokTask.showLogAndTsPrint("搜索下一个关键字：" + keyWords.get(nextIndex));
                                        Thread.sleep(2000);
                                        searchAndAutoLookVideo(nextIndex, keyWords, duration, likePercent, attentionPercent, commentPercent);
                                    }
                                } else {
                                    tikTokTask.onTaskErr("养号任务失败");
                                }
                            } else {
                                Thread.sleep(1000);
                                tikTokTask.changeTaskStatusToStart();
                            }
                        } else {
                            tikTokTask.onTaskErr("养号任务失败");
                        }
                    } else {
                        Thread.sleep(1000);
                        tikTokTask.changeTaskStatusToStart();
                    }
                } else {
                    Thread.sleep(1000);
                    tikTokTask.changeTaskStatusToStart();
                }
            } else {
                Thread.sleep(1000);
                tikTokTask.changeTaskStatusToStart();
            }
        } else {
            tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
            backOnce();
            Thread.sleep(2000);
            tikTokTask.changeTaskStatusToStart();
        }
    }


    public void backToTiktokMainPage() throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
        backOnce();
        Thread.sleep(2000);
        //重新设置任务状态
        tikTokTask.changeTaskStatusToStart();
    }


    /**
     * 普通养号任务
     *
     * @param duration 养号任务总时常
     * @param likePercent 点赞概率？%
     * @param attentionPercent 关注概率？%
     * @param commentPercent 评论概率？%
     */
    long startDoTaskTime;
    int lookedVideoSize;

    public void autoLookVideo(long duration, int likePercent, int attentionPercent, int commentPercent) throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        lookedVideoSize = 0;
        if (checkCurrentPageIsMainPage()) {
            //确保已经在首页了
            startDoTaskTime = System.currentTimeMillis();
            boolean isAutoLookFinish = startLoopLookVideo(false, duration, likePercent, attentionPercent, commentPercent);
            if (isAutoLookFinish) {
                //养号结束
                tikTokTask.showLogAndTsPrint("养号结束，共观看视频:" + lookedVideoSize + "条");
                tikTokTask.onTaskFinish();
            }else{
                tikTokTask.onTaskErr("养号任务失败");
            }
        } else {
            tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
            backOnce();
            Thread.sleep(2000);
            tikTokTask.changeTaskStatusToStart();
        }
    }

    private boolean startLoopLookVideo(boolean isSearchPage, long duration, int likePercent, int attentionPercent, int commentPercent) throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return false;
        }
        boolean isAutoLookFinish = false;
        while (System.currentTimeMillis() - startDoTaskTime < duration && tikTokTask.taskStatus != BaseTask.STOP) {
            //养号进行中
            //观看视频
            int singleVideoDuration = new Random().nextInt(46) + 15;
//            int singleVideoDuration = new Random().nextInt(4) + 1;
            if(!Constants.tiktokPackageName.equals(getCurrentPagePackageName())){
                if(isSearchPage){
                    tikTokTask.onTaskErr("未进入搜索视频的详情页");
                    return false;
                }else{
                    AppUtils.launchApp(Constants.tiktokPackageName);
                    tikTokTask.showLogAndTsPrint("重新打开Tiktok");
                    Thread.sleep(3000);
                }
            }
            if (isSearchPage) {
                AccessibilityNodeInfo topSearchEtNode = findNodeFirstById(FindIdResouresConfig.searchEtTopBtId);
                if (topSearchEtNode == null) {
                    tikTokTask.onTaskErr("未进入搜索视频的详情页");
                    return false;
                }
            }
            lookedVideoSize++;
            String videoName = getVideoName();
//            int singleVideoDuration = new Random().nextInt(6) + 5;
            LogUtils.i("当前视频观看" + singleVideoDuration + "秒");
            tikTokTask.showLogAndTsPrint("观看视频：" + videoName);
            try {
                Thread.sleep(singleVideoDuration * 1000);
                if(isForceStop){
                    isForceStop=false;
                    TsUtils.showTips("强制停止任务");
                    break;
                }
                if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
                    break;
                }
                //判断点赞
                checkAndClickLikeBt(likePercent);
                //判断关注
                checkAndAttentionBt(attentionPercent);
                //判断评论
                checkAndCommentBt(commentPercent);
                if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
                    break;
                }
                //滑动到下一个视频
                swipeToNextVideo();
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                tikTokTask.onTaskErr("养号任务失败");
                return false;
            }
        }
        if (tikTokTask!=null&&tikTokTask.taskStatus != BaseTask.STOP) {
            isAutoLookFinish = true;
        }
        return isAutoLookFinish;
    }

    private String getVideoName() {
        List<AccessibilityNodeInfo> accessibilityNodeInfos = findNodesById(FindIdResouresConfig.contentDescVideoNodeId);
        String videoName = "无标题";
        if (isNodeExist(accessibilityNodeInfos)) {
            int index = 0;
            if (accessibilityNodeInfos.size() > 2) {
                index = 1;
            }
            AccessibilityNodeInfo nodeInfo = accessibilityNodeInfos.get(index);
            while (nodeInfo != null &&
                    nodeInfo.getChildCount() != 0) {
                nodeInfo = nodeInfo.getChild(0);
            }
            if (nodeInfo != null) {
                if (nodeInfo.getText() != null) {
                    videoName = nodeInfo.getText().toString();
                }
            }
        }
        if (videoName.length() > 12) {
            videoName = videoName.substring(0, 12) + "...";
        }
        return videoName;
    }

    private String getUserNickName() {
        List<AccessibilityNodeInfo> accessibilityNodeInfos = findNodesById(FindIdResouresConfig.videoUserNickNameId);
        String userNickName = "";
        if (isNodeExist(accessibilityNodeInfos)) {
            LogUtils.v("用户名字的节点共计：" + accessibilityNodeInfos.size() + "个");
            AccessibilityNodeInfo accessibilityNodeInfo = accessibilityNodeInfos.get(0);
            if (accessibilityNodeInfos.size() > 2) {
                accessibilityNodeInfo = accessibilityNodeInfos.get(1);
            }
            while (accessibilityNodeInfo != null && accessibilityNodeInfo.getChildCount() > 0) {
                accessibilityNodeInfo = accessibilityNodeInfo.getChild(0);
            }
            if (accessibilityNodeInfo != null) {
                userNickName = accessibilityNodeInfo.getText().toString();
            }
        }
        return userNickName;
    }


    public void swipeYearScrollBarToBottom(int count) {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        tikTokTask.showLogAndTsPrint("滑动到下一页");
        int startX = new Random().nextInt(50) + ScreenUtils.getAppScreenWidth() / 2;
        int endX = new Random().nextInt(20) + ScreenUtils.getAppScreenWidth() / 2;
        int startY = ScreenUtils.getAppScreenHeight() - new Random().nextInt(250) - 150;
        int endY = new Random().nextInt(50) + ScreenUtils.getAppScreenHeight() / 5;
        LogUtils.v("startY=" + startY + ",endY=" + endY + ",startX=" + startX + ",endX=" + endX);
        swipe(startX, startY, endX, endY, 700);
        try {
            Thread.sleep(1000);
            count--;
            if (count > 0) {
                swipeYearScrollBarToBottom(count);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public void swipeToTop(int count) {
        tikTokTask.showLogAndTsPrint("滑动到顶部");
        int startX = new Random().nextInt(50) + ScreenUtils.getAppScreenWidth() / 2;
        int endX = new Random().nextInt(20) + ScreenUtils.getAppScreenWidth() / 2;
        int startY = new Random().nextInt(50) + ScreenUtils.getAppScreenHeight() / 5;
        int endY = ScreenUtils.getAppScreenHeight() - new Random().nextInt(250) - 150;
        LogUtils.v("startY=" + startY + ",endY=" + endY + ",startX=" + startX + ",endX=" + endX);
        swipe(startX, startY, endX, endY, 700);
        try {
            Thread.sleep(1000);
            count--;
            if (count > 0) {
                swipeToTop(count);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 滑动观看下一条视频
     */
    public void swipeToNextVideo() {
        if (tikTokTask!=null&&tikTokTask.taskStatus == BaseTask.STOP) {
            return;
        }
        tikTokTask.showLogAndTsPrint("滑动到下一页");
        int startX = new Random().nextInt(50) + ScreenUtils.getAppScreenWidth() / 2;
        int endX = new Random().nextInt(20) + ScreenUtils.getAppScreenWidth() / 2;
        int startY = ScreenUtils.getAppScreenHeight() - new Random().nextInt(250) - 150;
        int endY = new Random().nextInt(50) + ScreenUtils.getAppScreenHeight() / 5;
        LogUtils.v("startY=" + startY + ",endY=" + endY + ",startX=" + startX + ",endX=" + endX);
        swipe(startX, startY, endX, endY, 700);
    }


    /**
     * 检测是否需要评论并进行对应操作
     *
     * @param commentPercent
     */
    private void checkAndCommentBt(int commentPercent) throws InterruptedException {
        if (tikTokTask!=null&&tikTokTask.taskStatus == BaseTask.STOP) {
            return;
        }
        LogUtils.v("判断是否需要评论");
        int needCommentClick = new Random().nextInt(100);
        if (needCommentClick <= commentPercent) {
            String videoName = getVideoName();
            tikTokTask.showLogAndTsPrint("评论作品：" + videoName);
            List<AccessibilityNodeInfo> nodeInfos = findNodesById(FindIdResouresConfig.commentBt1Id);
            List<AccessibilityNodeInfo> nodeInfos2 = findNodesById(FindIdResouresConfig.commentBt2Id);
            List<AccessibilityNodeInfo> nodeInfos3 = findNodesById(FindIdResouresConfig.commentBt3Id);
            if (isNodeExist(nodeInfos)) {
                comment(nodeInfos);
            } else if (isNodeExist(nodeInfos2)) {
                comment(nodeInfos2);
            } else if (isNodeExist(nodeInfos3)) {
                comment(nodeInfos3);
            } else {
                tikTokTask.onTaskErr("评论失败");
            }
        }
    }


    public void comment(List<AccessibilityNodeInfo> nodeInfos) throws InterruptedException {
        LogUtils.i("按钮的个数：" + nodeInfos.size());
        AccessibilityNodeInfo nodeInfo = null;
        for (int i = 0; i < nodeInfos.size(); i++) {
            if (nodeInfos.size() >= 3 && i == 0) {
                continue;
            }
            if (nodeInfos.get(i).getClassName().equals(FindIdResouresConfig.imageViewClassName)) {
                nodeInfo = nodeInfos.get(i);
                break;
            }
        }
        if (nodeInfo != null) {
            clickXy(nodeInfo);
            Thread.sleep(4000);
            AccessibilityNodeInfo emojiRootNodeInfo = findNodeFirstById(FindIdResouresConfig.commentEmojiRecycleViewId);
            if (emojiRootNodeInfo != null && emojiRootNodeInfo.getChildCount() > 0) {
                int size = emojiRootNodeInfo.getChildCount();
                int position = 0;
                int randSize = new Random().nextInt(5);
                for (int i = 0; i < randSize; i++) {
                    position = size - new Random().nextInt(size - 1);
                    while (position >= size) {
                        position--;
                    }
                    click(emojiRootNodeInfo.getChild(position));
                    Thread.sleep(1000);
                }
                LogUtils.v("点击表情，然后发送");
                AccessibilityNodeInfo sendNodeInfo = findNodeFirstById(FindIdResouresConfig.commentSendBtId);
                if (sendNodeInfo != null) {
                    clickXy(sendNodeInfo);
                    LogUtils.i("发送评论成功");
                    tikTokTask.showLogAndTsPrint("评论成功");
                    Thread.sleep(1000);
                    backOnce();
                    Thread.sleep(1000);
                } else {
                    backOnce();
                    LogUtils.e("发送评论失败");
                }
            } else {
                backOnce();
            }
        }
        Thread.sleep(2000);
    }


    /**
     * 检测是否需要评论并进行对应操作
     *
     * @param commentPercent
     */
    private boolean checkAndCommentBt(int commentPercent, String commentText) throws InterruptedException {
        boolean isCommentSuccess = false;
        if (tikTokTask!=null&&tikTokTask.taskStatus == BaseTask.STOP) {
            return false;
        }
        LogUtils.v("判断是否需要评论");
        int needCommentClick = new Random().nextInt(100);
        if (needCommentClick <= commentPercent) {
            String videoName = getVideoName();
            tikTokTask.showLogAndTsPrint("评论作品：" + videoName);
            List<AccessibilityNodeInfo> nodeInfos = findNodesByText(FindIdResouresConfig.commentBt1Id);
            List<AccessibilityNodeInfo> nodeInfos2 = findNodesById(FindIdResouresConfig.commentBt2Id);
            List<AccessibilityNodeInfo> nodeInfos3 = findNodesById(FindIdResouresConfig.commentBt3Id);
            if (isNodeExist(nodeInfos)) {
                isCommentSuccess = comment(nodeInfos, commentText);
            } else if (isNodeExist(nodeInfos2)) {
                isCommentSuccess = comment(nodeInfos2, commentText);
            } else if (isNodeExist(nodeInfos3)) {
                isCommentSuccess = comment(nodeInfos3, commentText);
            } else {
                tikTokTask.showLogAndTsPrint("找不到按钮id" + FindIdResouresConfig.commentBt1Id);
                Thread.sleep(4000);
                tikTokTask.onTaskErr("作品评论失败");
            }
        }
        return isCommentSuccess;
    }


    public boolean comment(List<AccessibilityNodeInfo> nodeInfos, String commentText) throws InterruptedException {
        boolean isCommentSuccess = false;
        AccessibilityNodeInfo nodeInfo = nodeInfos.get(0);
        if (nodeInfos.size() >= 3) {
            nodeInfo = nodeInfos.get(1);
        }
        clickXy(nodeInfo);
        Thread.sleep(4000);
        AccessibilityNodeInfo etNodeId = findNodeFirstById(FindIdResouresConfig.commentEtId);
        if (etNodeId != null) {
            setNodeText(etNodeId, commentText);
            tikTokTask.showLogAndTsPrint("设置评论:" + commentText);
            Thread.sleep(2000);
            AccessibilityNodeInfo sendNodeInfo = findNodeFirstById(FindIdResouresConfig.commentSendBtId);
            if (sendNodeInfo != null) {
                clickXy(sendNodeInfo);
                LogUtils.i("发送评论成功");
                tikTokTask.showLogAndTsPrint("评论成功");
                Thread.sleep(1000);
                AccessibilityNodeInfo etNodeId2 = findNodeFirstById(FindIdResouresConfig.commentEtId);
                if (etNodeId2 != null) {
                    backOnce();
                    Thread.sleep(1000);
                }
                isCommentSuccess = true;
            } else {
                AccessibilityNodeInfo etNodeId2 = findNodeFirstById(FindIdResouresConfig.commentEtId);
                if (etNodeId2 != null) {
                    backOnce();
                    Thread.sleep(1000);
                }
                tikTokTask.onTaskErr("作品评论失败");
                isCommentSuccess = false;
            }
        } else {
            backOnce();
            isCommentSuccess = false;
            Thread.sleep(2000);
            tikTokTask.onTaskErr("作品评论失败");
        }
        return isCommentSuccess;
    }


    /**
     * 养号——检测是否需要关注并做出对应操作
     *
     * @param attentionPercent
     */
    private void checkAndAttentionBt(int attentionPercent) {
        if (tikTokTask!=null&&tikTokTask.taskStatus == BaseTask.STOP) {
            return;
        }
        int needAttentionClick = new Random().nextInt(100);
        LogUtils.v("判断是否需要关注:" + needAttentionClick + "/" + attentionPercent);
        if (needAttentionClick <= attentionPercent) {
            String userNickName = getUserNickName();
            tikTokTask.showLogAndTsPrint("关注用户：" + userNickName);
            List<AccessibilityNodeInfo> nodeInfos = findNodesById(FindIdResouresConfig.attentionButtonId);
            if (isNodeExist(nodeInfos)) {
                LogUtils.i("按钮的个数：" + nodeInfos.size());
                AccessibilityNodeInfo nodeInfo = null;
                for (int i = 0; i < nodeInfos.size(); i++) {
                    if (nodeInfos.size() >= 3 && i == 0) {
                        continue;
                    }
                    if (nodeInfos.get(i).getClassName().equals(FindIdResouresConfig.imageViewClassName)) {
                        nodeInfo = nodeInfos.get(i);
                        break;
                    }
                }
                if (nodeInfo != null) {
                    clickXy(nodeInfo);
                }
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }


    /**
     * 养号——检测是否需要点赞并做出对应动作
     */
    private boolean checkAndClickLikeBt(int likePercent) {
        if (tikTokTask!=null&&tikTokTask.taskStatus == BaseTask.STOP) {
            return false;
        }
        LogUtils.v("判断是否需要点赞");
        int needLikeClick = new Random().nextInt(100);
        if (needLikeClick <= likePercent) {
            String videoName = getVideoName();
            tikTokTask.showLogAndTsPrint("点赞作品：" + videoName);
            clickLikeIconByNode();
        }
        return true;
    }


    public void doubleClickToLike() {
        try {
            accessibilityTool.clickScreen(service, 800, 500);
            Thread.sleep(30);
            accessibilityTool.clickScreen(service, 800, 500);
            Thread.sleep(30);
            accessibilityTool.clickScreen(service, 800, 500);
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public boolean clickLikeIconByNode() {
        List<AccessibilityNodeInfo> nodeInfos = findNodesById(FindIdResouresConfig.likeButtonId);
        if (isNodeExist(nodeInfos)) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            AccessibilityNodeInfo nodeInfo = null;
            if (nodeInfos.size() >= 3) {
                nodeInfo = nodeInfos.get(1);
            } else {
                nodeInfo = nodeInfos.get(0);
            }
            if (nodeInfo != null) {
                clickXy(nodeInfo);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 单个作品点赞
     *
     * @param duration 观看时长(毫秒)
     */
    public synchronized void singleWorksLike(long duration) throws InterruptedException {
        if (!checkCurrentPageIsMainPage()) {
            backOnce();
            Thread.sleep(2000);
            tikTokTask.changeTaskStatusToStart();
            return;
        }
        tikTokTask.showLogAndTsPrint("观看作品：" + getVideoName());
        Thread.sleep(duration);
        boolean isSuccess = checkAndClickLikeBt(100);
        if (isSuccess) {
            if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
                tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
                Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
            } else {
                backOnce();
                Thread.sleep(3000);
            }
            tikTokTask.onTaskFinish();
        } else {
            tikTokTask.onTaskErr("点赞失败");
            backOnce();
            Thread.sleep(3000);
        }
    }

    private boolean closeAttentionTipDialog() {
        boolean isCloseAttentionDialog = false;
        AccessibilityNodeInfo closeBtNode = findNodeFirstById(FindIdResouresConfig.closeAttentionDialogTipsId);
        AccessibilityNodeInfo attentionYouDialogCloseTopNode = findNodeFirstById(FindIdResouresConfig.attentionYouFriendTipsDialogCloseId);
        if (closeBtNode != null) {
            clickXy(closeBtNode);
            LogUtils.i("关闭关注弹框");
            tikTokTask.showLogAndTsPrint("关闭弹框");
            isCloseAttentionDialog = true;
        }
        if (attentionYouDialogCloseTopNode != null) {
            clickXy(attentionYouDialogCloseTopNode);
            LogUtils.i("关闭弹框");
            tikTokTask.showLogAndTsPrint("关闭弹框");
            isCloseAttentionDialog = true;
        }
        return isCloseAttentionDialog;
    }

    public boolean closeCustomTipDialog() {
        boolean isCloseCustomDialog = false;
        AccessibilityNodeInfo closeBtNode = findNodeFirstById(FindIdResouresConfig.tipsDialogId);
        if (closeBtNode != null && closeBtNode.getChildCount() > 0) {
            if (closeBtNode.getChildCount() == 1) {
                AccessibilityNodeInfo relativelayout = closeBtNode.getChild(0);
                if (relativelayout != null && relativelayout.getChildCount() >= 2 && relativelayout.getChild(1) != null) {
                    clickXy(relativelayout.getChild(1));
                    tikTokTask.showLogAndTsPrint("关闭弹框");
                    isCloseCustomDialog = true;
                }
            } else if (closeBtNode.getChildCount() == 2 && closeBtNode.getChild(1) != null) {
                clickXy(closeBtNode.getChild(1));
                tikTokTask.showLogAndTsPrint("关闭弹框");
                isCloseCustomDialog = true;
            }
        }

        AccessibilityNodeInfo closeAllowContractBtNode = findNodeFirstById(FindIdResouresConfig.tipsDialogP4Id);
        if (closeAllowContractBtNode != null && closeAllowContractBtNode.getChildCount() > 0) {
            if (closeAllowContractBtNode.getChildCount() == 1) {
                AccessibilityNodeInfo relativelayout = closeAllowContractBtNode.getChild(0);
                if (relativelayout != null && relativelayout.getChildCount() >= 2 && relativelayout.getChild(1) != null) {
                    clickXy(relativelayout.getChild(1));
                    tikTokTask.showLogAndTsPrint("关闭弹框");
                    isCloseCustomDialog = true;
                }
            } else if (closeAllowContractBtNode.getChildCount() == 2 && closeAllowContractBtNode.getChild(1) != null) {
                clickXy(closeAllowContractBtNode.getChild(1));
                tikTokTask.showLogAndTsPrint("关闭弹框");
                isCloseCustomDialog = true;
            }
        }
        return isCloseCustomDialog;
    }


    /**
     * 单个作品评论
     *
     * @param duration 观看时长(毫秒)
     */
    public synchronized void singleWorksComment(long duration, String commentText) throws InterruptedException {
        if (!checkCurrentPageIsMainPage()) {
            backOnce();
            Thread.sleep(2000);
            tikTokTask.changeTaskStatusToStart();
            return;
        }
        tikTokTask.showLogAndTsPrint("观看作品：" + getVideoName());
        Thread.sleep(duration);
        boolean isCommentSuccess = checkAndCommentBt(100, commentText);
        if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
            tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
            Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
        } else {
            backOnce();
            Thread.sleep(3000);
        }
        if (isCommentSuccess) {
            tikTokTask.onTaskFinish();
        } else {
            tikTokTask.onTaskErr("评论失败");
        }
    }


    /**
     * 搜索并关注单个用户
     * tdzzzz._
     * sanajan9800
     */
    public void attentionSingleUser(String keyWord) throws InterruptedException {
        if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
            return;
        }
        if (checkCurrentPageIsMainPage()) {
            AccessibilityNodeInfo imageNode = getMainSearchIconNode();
            if (imageNode != null) {
                click(imageNode);
                Thread.sleep(2000);
                tikTokTask.showLogAndTsPrint("进入搜索页面");
                AccessibilityNodeInfo searchEtNode = findNodeFirstById(FindIdResouresConfig.searchEtId);
                if (searchEtNode != null) {
                    setNodeText(searchEtNode, keyWord);
                    Thread.sleep(2000);
                    AccessibilityNodeInfo searchBtNode = findNodeFirstById(FindIdResouresConfig.searchBtId);
                    if (searchBtNode != null) {
                        clickXy(searchBtNode);
                        tikTokTask.showLogAndTsPrint("搜索关键字");
                        Thread.sleep(8000);
                        AccessibilityNodeInfo topNode = findNodeFirstById(FindIdResouresConfig.searchPagePersonGroupId);
                        AccessibilityNodeInfo attentionNode = findNodeFirstById(FindIdResouresConfig.searchPagePersonAttentionBtId);
                        if (topNode != null && attentionNode != null) {
                            clickXy(attentionNode);
                            tikTokTask.showLogAndTsPrint("关注@" + keyWord + "成功");
                            Thread.sleep(2000);
                            if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
                                tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
                                Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
                            }
                            tikTokTask.onTaskFinish();
                        } else {
                            tikTokTask.showLogAndTsPrint("未找到此用户名信息，任务结束");
                            Thread.sleep(1000);
                            tikTokTask.onTaskErr("未找到此用户名信息");
                        }
                    } else {
                        Thread.sleep(1000);
                        tikTokTask.changeTaskStatusToStart();
                    }
                } else {
                    Thread.sleep(1000);
                    tikTokTask.changeTaskStatusToStart();
                }
            } else {
                Thread.sleep(1000);
                tikTokTask.changeTaskStatusToStart();
            }
        } else {
            tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
            backOnce();
            Thread.sleep(2000);
            tikTokTask.changeTaskStatusToStart();
        }
    }


    /**
     * 搜索并私信单个用户
     *
     * @param userName
     */
    public boolean chatWithSingleUser(String userName, String chatContent) throws InterruptedException {
        boolean isChatMsgSendSuccess = false;
        if (checkCurrentPageIsMainPage()) {
            AccessibilityNodeInfo imageNode = getMainSearchIconNode();
            if (imageNode != null) {
                click(imageNode);
                Thread.sleep(2000);
                tikTokTask.showLogAndTsPrint("进入搜索页面");
                AccessibilityNodeInfo searchEtNode = findNodeFirstById(FindIdResouresConfig.searchEtId);
                if (searchEtNode != null) {
                    setNodeText(searchEtNode, userName);
                    Thread.sleep(2000);
                    AccessibilityNodeInfo searchBtNode = findNodeFirstById(FindIdResouresConfig.searchBtId);
                    if (searchBtNode != null) {
                        clickXy(searchBtNode);
                        tikTokTask.showLogAndTsPrint("搜索关键字");
                        Thread.sleep(8000);
                        AccessibilityNodeInfo topNode = findNodeFirstById(FindIdResouresConfig.searchPagePersonGroupId);
                        AccessibilityNodeInfo imageHeadNode = findNodeFirstById(FindIdResouresConfig.searchPagePersonImageHeadId);
                        if (topNode != null && imageHeadNode != null) {
                            clickXy(imageHeadNode);
                            Thread.sleep(2000);
                            LogUtils.i("进入个人信息页面");
                            AccessibilityNodeInfo chatWithOtherNode = findNodeFirstById(FindIdResouresConfig.otherChatBtId);
                            if (chatWithOtherNode != null) {
                                clickXy(chatWithOtherNode);
                                tikTokTask.showLogAndTsPrint("点击消息/关注按钮进入聊天页");
                                Thread.sleep(4000);
                                chatWithOtherNode = findNodeFirstById(FindIdResouresConfig.otherChatBtId);
                                if (chatWithOtherNode != null) {
                                    clickXy(chatWithOtherNode);
                                    tikTokTask.showLogAndTsPrint("点击/关注按钮进入聊天页");
                                    Thread.sleep(3000);
                                }
                                //防止底部弹个框起来
                                AccessibilityNodeInfo bottomDialogNodeId = findNodeFirstById(FindIdResouresConfig.bottomDialogNodeId);
                                if(bottomDialogNodeId!=null){
                                    clickXy(bottomDialogNodeId);
                                    Thread.sleep(4000);
                                }
                                AccessibilityNodeInfo chatWithOtherEtNodeId = findNodeFirstById(FindIdResouresConfig.otherChatBottomEtBtId);
                                if (chatWithOtherEtNodeId != null) {
                                    setNodeText(chatWithOtherEtNodeId, chatContent);
                                    tikTokTask.showLogAndTsPrint("输入内容");
                                    Thread.sleep(3000);
                                    List<AccessibilityNodeInfo> chatWithOtherSendNodeIds = findNodesById(FindIdResouresConfig.otherChatBottomSendBtId);
                                    if (isNodeExist(chatWithOtherSendNodeIds)) {
                                        Thread.sleep(3000);
                                        int index=chatWithOtherSendNodeIds.size()-1;
                                        if(chatWithOtherSendNodeIds.size()>=3){
                                            index=1;
                                        }
                                        AccessibilityNodeInfo chatWithOtherSendNodeId = chatWithOtherSendNodeIds.get(index);
                                        if (chatWithOtherSendNodeId != null) {
                                            clickXy(chatWithOtherSendNodeId);
                                            tikTokTask.showLogAndTsPrint("发送消息");
                                            Thread.sleep(3000);
                                            AccessibilityNodeInfo chatWithOtherFailTextNodeId = findNodeFirstById(FindIdResouresConfig.otherChatBottomSendFailTextId);
                                            if (chatWithOtherFailTextNodeId != null) {
                                                if(chatWithOtherFailTextNodeId.getChild(0)!=null){
                                                    if("已发送".contentEquals(chatWithOtherFailTextNodeId.getChild(0).getText())){
                                                        tikTokTask.showLogAndTsPrint("消息发送成功了");
                                                        Thread.sleep(2000);
                                                        if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
                                                            tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
                                                            Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
                                                        }
                                                        isChatMsgSendSuccess = true;
                                                    }else{
                                                        tikTokTask.showLogAndTsPrint("消息发送失败了");
                                                        Thread.sleep(2000);
                                                        if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
                                                            tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
                                                            Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
                                                        }
                                                    }
                                                }else{
                                                    LogUtils.i("消息发送失败了");
                                                    Thread.sleep(2000);
                                                    if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
                                                        tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
                                                        Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
                                                    }
                                                }
                                            } else {
                                                LogUtils.i("消息发送失败了");
                                                Thread.sleep(2000);
                                                if (tikTokTask.serverTaskDataBean.getWaitTime() > 0) {
                                                    tikTokTask.showLogAndTsPrint("多任务间隔时间停留" + tikTokTask.serverTaskDataBean.getWaitTime() / 1000 + "s");
                                                    Thread.sleep(tikTokTask.serverTaskDataBean.getWaitTime());
                                                }
                                            }
                                        } else {
                                            tikTokTask.onTaskErr("未找到聊天发送按钮id");
                                            Thread.sleep(1000);
                                        }
                                    } else {
                                        tikTokTask.onTaskErr("未找到发送按钮id");
                                        Thread.sleep(1000);
                                    }
                                } else {
                                    tikTokTask.onTaskErr("无法进入聊天页面");
                                    Thread.sleep(1000);
                                }
                            } else {
                                tikTokTask.onTaskErr("无法进入聊天页面");
                                Thread.sleep(1000);
                            }
                        } else {
                            tikTokTask.onTaskErr("未找到此用户名信息");
                            Thread.sleep(1000);
                        }
                    } else {
                        Thread.sleep(1000);
                        tikTokTask.changeTaskStatusToStart();
                    }
                } else {
                    Thread.sleep(1000);
                    tikTokTask.changeTaskStatusToStart();
                }
            } else {
                Thread.sleep(1000);
                tikTokTask.changeTaskStatusToStart();
            }
        }else{
            tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
            backOnce();
            return chatWithSingleUser(userName, chatContent);
        }
        return isChatMsgSendSuccess;
    }


    /**
     * 判断是否在选择生日的页面，如果在则滑动选择一个年份并前往下一页
     * @return
     */
    public boolean isInBirthDaySelectPageAndScrollYear() throws InterruptedException {
        AccessibilityNodeInfo birthYearNode = findNodeFirstById(FindIdResouresConfig.register_birthday_year_scroll1NodeId);
        AccessibilityNodeInfo birthMonthNode = findNodeFirstById(FindIdResouresConfig.register_birthday_month_scroll1NodeId);
        AccessibilityNodeInfo birthDayNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_scroll1NodeId);
        AccessibilityNodeInfo nextBtNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_next_bt_NodeId);
        if(birthYearNode!=null&&birthMonthNode!=null&&birthDayNode!=null&&nextBtNode!=null){
            tikTokTask.showLogAndTsPrint("模拟填写随机生日信息");
            swipeYearScrollBarToBottom(birthYearNode,new Random().nextInt(5)+11,1000);
            swipeYearScrollBarToBottom(birthMonthNode,new Random().nextInt(2)+4,700);
            swipeYearScrollBarToBottom(birthDayNode,new Random().nextInt(2)+4,700);
            tikTokTask.showLogAndTsPrint("点击进入下一页");
            clickXy(nextBtNode);
             birthYearNode = findNodeFirstById(FindIdResouresConfig.register_birthday_year_scroll1NodeId);
             birthMonthNode = findNodeFirstById(FindIdResouresConfig.register_birthday_month_scroll1NodeId);
             birthDayNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_scroll1NodeId);
             int tryTime=0;
            while (birthYearNode!=null&&birthMonthNode!=null&&birthDayNode!=null&&tryTime<10){
                Thread.sleep(1000);
                tryTime++;
                birthYearNode = findNodeFirstById(FindIdResouresConfig.register_birthday_year_scroll1NodeId);
                birthMonthNode = findNodeFirstById(FindIdResouresConfig.register_birthday_month_scroll1NodeId);
                birthDayNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_scroll1NodeId);
            }
            Thread.sleep(2000);
            birthYearNode = findNodeFirstById(FindIdResouresConfig.register_birthday_year_scroll1NodeId);
            birthMonthNode = findNodeFirstById(FindIdResouresConfig.register_birthday_month_scroll1NodeId);
            birthDayNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_scroll1NodeId);
            return birthYearNode == null || birthMonthNode == null || birthDayNode == null;
        }
        return false;
    }


    public boolean isInBirthDaySelectOnlyResult(){
        AccessibilityNodeInfo birthYearNode = findNodeFirstById(FindIdResouresConfig.register_birthday_year_scroll1NodeId);
        AccessibilityNodeInfo birthMonthNode = findNodeFirstById(FindIdResouresConfig.register_birthday_month_scroll1NodeId);
        AccessibilityNodeInfo birthDayNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_scroll1NodeId);
        AccessibilityNodeInfo nextBtNode = findNodeFirstById(FindIdResouresConfig.register_birthday_day_next_bt_NodeId);
        if(birthYearNode!=null&&birthMonthNode!=null&&birthDayNode!=null&&nextBtNode!=null){
            return true;
        }
        return false;
    }


    /**
     * 是否从选择标签页面进入到开始观看页面
     * @return
     * @throws InterruptedException
     */
    public boolean isFirstInTikTokAndInSelectTagAc() throws InterruptedException {
        List<AccessibilityNodeInfo> tagNodes = findNodesById(FindIdResouresConfig.register_select_tag_node_id);
        AccessibilityNodeInfo jumpBtNode = findNodeFirstById(FindIdResouresConfig.register_jump_to_next_bt_node_id);
        if(isNodeExist(tagNodes)&&tagNodes.size()>=2&&jumpBtNode!=null){
            tikTokTask.showLogAndTsPrint("跳过选择标签");
            clickXy(jumpBtNode);
            Thread.sleep(3000);
            return true;
        }
        List<AccessibilityNodeInfo> jumpNode2 = findNodesByText("跳过");
        if(!MyUtils.isEmpty(jumpNode2)){
            clickXy(jumpNode2.get(0));
            Thread.sleep(2000);
            return true;
        }
        return false;
    }


    /**
     * 是否成功从开始观看页面进入到下一页
     * @return
     * @throws InterruptedException
     */
    public boolean isEnterInStartLookNextPage() throws InterruptedException {
        AccessibilityNodeInfo startLook = findNodeFirstById(FindIdResouresConfig.register_start_look_tiktok_node_id);
        if(startLook!=null){
            clickXy(startLook);
            tikTokTask.showLogAndTsPrint("进入tiktok");
            Thread.sleep(8000);
            AccessibilityNodeInfo firstCenterId = findNodeFirstById(FindIdResouresConfig.close_center_first_inner_dialog_sure_bt);
            if(firstCenterId!=null){
                clickXy(firstCenterId);
                tikTokTask.showLogAndTsPrint("关闭中间弹框第一次");
                Thread.sleep(8000);
            }
            tikTokTask.showLogAndTsPrint("等待出第二次弹框");
            Thread.sleep(8000);
            closeCustomTipDialog();
            Thread.sleep(3000);
            List<AccessibilityNodeInfo> nodes = AccessibilityTool.getInstance().findNodesByText(null, null, service, "上滑查看更多视频");
            if(isNodeExist(nodes)){
                swipeYearScrollBarToBottom(1);
                Thread.sleep(2000);
            }
            AccessibilityNodeInfo swipeNodeImageNode =findNodeFirstById(FindIdResouresConfig.swipe_center_tips_node_id);
            if(swipeNodeImageNode!=null){
                swipeYearScrollBarToBottom(1);
            }
            return true;
        }else{
            List<AccessibilityNodeInfo> nodes = AccessibilityTool.getInstance().findNodesByText(null, null, service, "上滑查看更多视频");
            if(isNodeExist(nodes)){
                swipeYearScrollBarToBottom(1);
            }
            AccessibilityNodeInfo swipeNodeImageNode =findNodeFirstById(FindIdResouresConfig.swipe_center_tips_node_id);
            if(swipeNodeImageNode!=null){
                swipeYearScrollBarToBottom(1);
            }
            backOnce();
            Thread.sleep(3000);
            tikTokTask.changeTaskStatusToStart();
        }
        return false;
    }

    /**
     * 判断是否在注册方式选择页面、手机还是邮箱有tab和输入框的页面
     * @return
     * @throws InterruptedException
     */
    public boolean isInRegisterSelectWayToReg(int registerType,String accountPhoneOrEmail,String frontStr,String pwdStr,String nickNameStr) throws InterruptedException {
        boolean isEnterInRegisterActivity=false;
        AccessibilityNodeInfo cancelDialog = findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
        if(cancelDialog!=null){
            tikTokTask.showLogAndTsPrint("关闭弹框");
            clickXy(cancelDialog);
            Thread.sleep(3000);
        }
        List<AccessibilityNodeInfo> tabNodes = findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
        if(isNodeExist(tabNodes)&&tabNodes.size()>=2){
            isEnterInRegisterActivity=true;
            tikTokTask.showLogAndTsPrint("已进入注册账号输入页面");
            AccessibilityNodeInfo registerByPhoneTab = tabNodes.get(0);
            AccessibilityNodeInfo registerByEmailTab = tabNodes.get(1);
            if(registerType==0){
                //手机号注册
                clickXy(registerByPhoneTab);
                tikTokTask.showLogAndTsPrint("切换到手机号注册");
                Thread.sleep(2000);
                dealWithFrontCode();
                AccessibilityNodeInfo editPhoneNodeId = findNodeFirstById(FindIdResouresConfig.register_phone_or_email_edit_tel_node);
                if(editPhoneNodeId!=null) {
                    //区号选择完毕之后开始输入手机号
                    setNodeText(editPhoneNodeId, accountPhoneOrEmail);
                    tikTokTask.showLogAndTsPrint("输入账号："+accountPhoneOrEmail);
                    Thread.sleep(2000);
//                    AccessibilityTool.getInstance().backOnce(service);
//                    tikTokTask.showLogAndTsPrint("关闭键盘");
//                    Thread.sleep(2000);
                    AccessibilityNodeInfo btNextTextNode = findNodeFirstById(FindIdResouresConfig.register_next_bt_node_id);
                    if(btNextTextNode!=null){
                        clickXy(btNextTextNode);
//                        Thread.sleep(8000);
                        long time=0;
                        boolean isNotEnterInNext=isNodeExist(findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId))&&findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId).size()>=2;
                        while (time<30&&isNotEnterInNext){
                            Thread.sleep(2000);
                            isNotEnterInNext=isNodeExist(findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId))&&findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId).size()>=2;
                            time++;
                        }
                        tabNodes = findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                        if(isNodeExist(tabNodes)&&tabNodes.size()>=2){
                            tikTokTask.onTaskErr("无法进入下一步");
                            return false;
                        }
                        inputPwdAndNickName(accountPhoneOrEmail,registerType,pwdStr,nickNameStr);
//                        boolean isDealSuccess = dealWithImageVerify(registerType);
//                        if(isDealSuccess){
//
//                        }else{
//                            tikTokTask.onTaskErr("图形验证码验证失败");
//                        }
                    }else{
                        Thread.sleep(2000);
                        List<AccessibilityNodeInfo> itemNodes = findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                        AccessibilityNodeInfo bottomChangeNode = findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                        if (isNodeExist(itemNodes) && bottomChangeNode != null) {
                            return false;
                        }else{
                            tikTokTask.onTaskErr("无法进入下一步");
                        }
                    }
                }
            }else{
                //邮箱注册
                clickXy(registerByEmailTab);
                tikTokTask.showLogAndTsPrint("切换到邮箱注册");
                Thread.sleep(2000);
                AccessibilityNodeInfo editEmailNodeId = findNodeFirstById(FindIdResouresConfig.register_phone_or_email_edit_tel_node);
                if(editEmailNodeId!=null) {
                    //区号选择完毕之后开始输入手机号
                    setNodeText(editEmailNodeId, accountPhoneOrEmail);
                    tikTokTask.showLogAndTsPrint("输入账号："+accountPhoneOrEmail);
                    Thread.sleep(2000);
//                    AccessibilityTool.getInstance().backOnce(service);
//                    tikTokTask.showLogAndTsPrint("关闭键盘");
//                    Thread.sleep(2000);
                    AccessibilityNodeInfo btNextNodeId = findNodeFirstById(FindIdResouresConfig.register_next_bt_node_id);
                    if(btNextNodeId!=null){
                        clickXy(btNextNodeId);
//                        Thread.sleep(8000);
//                        boolean isDealSuccess = dealWithImageVerify(registerType);
                        long time=0;
                        boolean isNotEnterInNext=isNodeExist(findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId))&&findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId).size()>=2;
                        while (time<15&&isNotEnterInNext){
                            Thread.sleep(2000);
                            isNotEnterInNext=isNodeExist(findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId))&&findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId).size()>=2;
                            time++;
                        }
                        tabNodes = findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                        if(isNodeExist(tabNodes)&&tabNodes.size()>=2){
                            tikTokTask.onTaskErr("无法进入下一步");
                            return false;
                        }
                        inputPwdAndNickName(accountPhoneOrEmail, registerType, pwdStr,nickNameStr);
                    }else{
                        Thread.sleep(2000);
                        List<AccessibilityNodeInfo> itemNodes = findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                        AccessibilityNodeInfo bottomChangeNode = findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                        if (isNodeExist(itemNodes) && bottomChangeNode != null) {
                            return false;
                        }else {
                            tikTokTask.onTaskErr("无法进入下一步");
                        }
                    }
                }
            }
        }
        return isEnterInRegisterActivity;
    }

    /**
     * 输入密码和昵称执行最后的注册流程
     * @throws InterruptedException
     */
    public void inputPwdAndNickName(String accountPhoneOrEmail, int registerType, String pwdStr, String nickNameStr) throws InterruptedException {
        Thread.sleep(8000);
        if(registerType==1) {
            //邮箱注册
            AccessibilityNodeInfo inputPwdNode = findNodeFirstById(FindIdResouresConfig.register_input_pwd_id);
            if (inputPwdNode != null) {
                tikTokTask.showLogAndTsPrint("设置密码："+pwdStr);
                setNodeText(inputPwdNode, pwdStr);
                Thread.sleep(3000);
                AccessibilityNodeInfo nextStepNode = findNodeFirstById(FindIdResouresConfig.register_next_bt_node_id);
                if(nextStepNode!=null) {
                    clickXy(nextStepNode);
                    tikTokTask.showLogAndTsPrint("等待图片验证码");
                    AccessibilityNodeInfo dialogNode = findNodeFirstById(FindIdResouresConfig.register_dialog_node);
                    while (dialogNode!=null){
                        Thread.sleep(2000);
                        dialogNode = findNodeFirstById(FindIdResouresConfig.register_dialog_node);
                        if(dialogNode==null){
                            break;
                        }
                    }
                    allowSystemPermission();
                    AccessibilityNodeInfo jumpBt = findNodeFirstById(FindIdResouresConfig.register_jump_bt_id);
                    //密码规则按钮
                    AccessibilityNodeInfo regSetNickName1 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt1_id);
                    AccessibilityNodeInfo regSetNickName2 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt2_bt_id);
                    if(jumpBt!=null&&regSetNickName1!=null&&regSetNickName2!=null){
                        dealWithRegisterSuccess(accountPhoneOrEmail,false,0,0);
                        return;
                    }
                    swipeSeekBar(accountPhoneOrEmail, false,0);
                }else{
                    //键盘挡住了返回一下
                    backOnce();
                    Thread.sleep(2000);
                    nextStepNode = findNodeFirstById(FindIdResouresConfig.register_next_bt_node_id);
                    if(nextStepNode==null){
                        tikTokTask.onTaskErr("无法点击下一步");
                    }else {
                        clickXy(nextStepNode);
                        tikTokTask.showLogAndTsPrint("确定密码等待旋转验证码");
                        AccessibilityNodeInfo dialogNode = findNodeFirstById(FindIdResouresConfig.register_dialog_node);
                        while (dialogNode!=null){
                            Thread.sleep(2000);
                            dialogNode = findNodeFirstById(FindIdResouresConfig.register_dialog_node);
                            if(dialogNode==null){
                                break;
                            }
                        }
                        Thread.sleep(8000);
                        swipeSeekBar(accountPhoneOrEmail, false,0);
                    }
                }
            } else {
                tikTokTask.onTaskErr("进入密码输入页面失败");
            }
        }else{
            //手机号注册
            AccessibilityNodeInfo inputPwdNode = findNodeFirstById(FindIdResouresConfig.register_input_phone_code_edit_id);
            AccessibilityNodeInfo reSendCodeNode = findNodeFirstById(FindIdResouresConfig.register_re_send_phone_code_bt_id);
            if(inputPwdNode!=null&&reSendCodeNode!=null){
                getPhoneCode(new OnVerifyCodeGetListener() {
                    @Override
                    public void onVerifyCodeGet(String verifyCode) throws InterruptedException {
                        setNodeText(inputPwdNode,verifyCode);
                        tikTokTask.showLogAndTsPrint("输入验证码");
                        Thread.sleep(3000);

                    }
                });
            }else{
                tikTokTask.onTaskErr("无法输入验证码");
            }
        }

    }

    public void getLength(String filePath, int seekBarCanScroll, boolean isSwipeType, OnLengthGetListener onLengthGetListener) throws InterruptedException {
//        seekBarCanScroll=431;
        // 读取图片base64编码数据
        String captchaData = null;
        int type=1121;//旋转类型
        if(isSwipeType){
            //水平滑块类型
            type=1318;
        }
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            captchaData = BingTopDama.getImageStr(filePath);
            // post图片数据，账号信息，进行打码
            String returnStr = BingTopDama.sendPost(
                    "http://www.bingtop.com/ocr/upload/",
                    "username="+Constants.userName+"&password="+Constants.password+"&captchaType="+type+"&captchaData="+captchaData,"UTF-8"
            );
            if(MyUtils.isEmpty(returnStr)){
                tikTokTask.onTaskErr("滑块识别失败");
                return;
            }
            Message message1=Message.obtain();
            message1.obj=returnStr;
            EventBus.getDefault().post(message1);
            RecognizeInfo recognizeInfo=GsonUtils.fromJson(returnStr,RecognizeInfo.class);
            LogUtils.i("获取到的图片识别信息："+returnStr);
            if(isSwipeType&&onLengthGetListener!=null){
                //水平滑块类型
            }else{
                //旋转类型
                int rate = Integer.parseInt(recognizeInfo.getData().getRecognition());//角度
                int scrollLength=seekBarCanScroll*rate/180;
                MsgTaskManger.showLog("滑动角度："+recognizeInfo.getData().getRecognition()+",code类型="+type+",滑道总长度："+seekBarCanScroll+",计算出的滑动距离："+scrollLength);
                TsUtils.showTips("滑动角度："+recognizeInfo.getData().getRecognition()+",code类型="+type+",滑道总长度："+seekBarCanScroll+",计算出的滑动距离："+scrollLength);
//                TsUtils.showTips("滑动滑块" + scrollLength + "像素");
                onLengthGetListener.onLengthGet(scrollLength);
            }
        }else{
            tikTokTask.onTaskErr("设备版本不支持该功能");
        }
    }


    public interface OnLengthGetListener{
        void onLengthGet(int length) throws InterruptedException;
    }


    public  void swipeSeekBar(String accountPhoneOrEmail,boolean isSwipeType,int tryTimes) throws InterruptedException {
        AccessibilityNodeInfo toManyNode = findNodeFirstById(FindIdResouresConfig.request_to_many_text_id);
        if(toManyNode!=null){
            tikTokTask.onTaskErr("注册被风控，提示访问太频繁！");
            return;
        }
        Thread.sleep(5000);
        allowSystemPermission();
        AccessibilityNodeInfo jumpBt = findNodeFirstById(FindIdResouresConfig.register_jump_bt_id);
        //密码规则按钮
        AccessibilityNodeInfo regSetNickName1 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt1_id);
        AccessibilityNodeInfo regSetNickName2 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt2_bt_id);
        if(jumpBt!=null&&regSetNickName1!=null&&regSetNickName2!=null){
            dealWithRegisterSuccess(accountPhoneOrEmail,false,tryTimes,0);
            return;
        }
        List<AccessibilityNodeInfo> seekBarNodes = AccessibilityTool.getInstance().findNodesByIdPlus(null, null, service, FindIdResouresConfig.verifyImageCodeSwipeTypeForceNodeId);
        if(!MyUtils.isEmpty(seekBarNodes)){
            AccessibilityNodeInfo seekBarNode = seekBarNodes.get(0);
            Rect rect=new Rect();
            seekBarNode.getBoundsInScreen(rect);
            int startX=(rect.left+rect.right)/2;
            int startY=(rect.top+rect.bottom)/2;
            int endY=(rect.top+rect.bottom)/2;
            List<AccessibilityNodeInfo> captcha_containerNode = AccessibilityTool.getInstance().findNodesByIdPlus(null,null,service, FindIdResouresConfig.captcha_container);
            if(isNodeExist(captcha_containerNode)&&captcha_containerNode.get(0)!=null&&captcha_containerNode.get(0).getChildCount()>0){
                AccessibilityNodeInfo dialog = captcha_containerNode.get(0).getChild(0);
                if(dialog!=null&&dialog.getChildCount()>2&&dialog.getChild(1).getChildCount()>0){
                    AccessibilityNodeInfo imageNode = dialog.getChild(1).getChild(0);
                    AccessibilityNodeInfo seekBarRootNode = dialog.getChild(2);

                    Rect rectSeekBar=new Rect();
                    seekBarRootNode.getBoundsInScreen(rectSeekBar);

                    Rect rect2=new Rect(194,444,526,810);
//                    imageNode.getBoundsInScreen(rect2);

                    int seekBarCanScroll=rectSeekBar.width()-rect.width();//可滑动的距离
                    File directory =BingTopDama.getRootDirectory();
                    tikTokTask.showLogAndTsPrint("处理图片验证码");
                    Bitmap bitmap = BingTopDama.takeScreenshotAndSaveToFilePath(accountPhoneOrEmail);
                    if(bitmap!=null){
                       boolean isCropSuccess= ImageCropper.cropImage(bitmap,accountPhoneOrEmail,rect2);
                       if(isCropSuccess){
                           //等待图片处理完成
                           Thread.sleep(3000);
                           tikTokTask.showLogAndTsPrint("AI识别验证码中");
                           // 构建文件路径
                           File file = new File(directory+"/"+accountPhoneOrEmail+"_crop.jpg");
                           if(file.exists()&&file.isFile()) {
                               int finalTryTimes = tryTimes;
                               getLength(file.getAbsolutePath(),seekBarCanScroll,isSwipeType, new OnLengthGetListener() {
                                   @Override
                                   public void onLengthGet(int swipeLength) throws InterruptedException {
                                       int moveX = swipeLength;
                                       int endX = startX+ moveX;
                                       long duration;
                                       tikTokTask.showLogAndTsPrint("旋转图片验证码");
                                       if(moveX>200){
                                           duration=1500;
                                       }else{
                                           duration=3000;
                                       }
                                       swipe(startX, startY, endX, endY, duration);
                                       Thread.sleep(duration+1000);
                                       File file = new File(BingTopDama.getRootDirectory()+"/"+accountPhoneOrEmail+"_crop.jpg");
                                       deleteFilePath(file);
                                       File file2 = new File(BingTopDama.getRootDirectory()+"/"+accountPhoneOrEmail+".jpg");
                                       deleteFilePath(file2);
                                       Thread.sleep(10000);
                                       dealWithRegisterSuccess(accountPhoneOrEmail,isSwipeType,finalTryTimes,0);
                                   }
                               });
                       }else{
                           tikTokTask.onTaskErr("图片裁剪文件保存失败");
                       }
                    }else{
                        tikTokTask.onTaskErr("图片裁剪失败");
                    }
                    }else{
                        tikTokTask.onTaskErr("图片未保存成功");
                    }

                }else{
                    tikTokTask.onTaskErr("无法截取旋转验证码图片");
                }
            }else{
                tikTokTask.onTaskErr("无法截取旋转验证码图片");
            }
        }else{
            allowSystemPermission();
            jumpBt = findNodeFirstById(FindIdResouresConfig.register_jump_bt_id);
            //密码规则按钮
            regSetNickName1 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt1_id);
            regSetNickName2 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt2_bt_id);
            if(jumpBt!=null&&regSetNickName1!=null&&regSetNickName2!=null){
                dealWithRegisterSuccess(accountPhoneOrEmail,false,tryTimes,0);
                return;
            }
             if(tryTimes>=3){
                 tikTokTask.onTaskErr("未找到验证码框");
             }else{
                 Thread.sleep(8000);
                 tryTimes++;
                 swipeSeekBar(accountPhoneOrEmail,isSwipeType,tryTimes);
             }
        }
    }

    /**
     * 在邮箱注册密码验证通过之后执行
     */
    private void dealWithRegisterSuccess(String accountPhoneOrEmail, boolean isSwipeType, int finalTryTimes,int tryJumpTimes) throws InterruptedException {
        AccessibilityNodeInfo toManyNode = findNodeFirstById(FindIdResouresConfig.request_to_many_text_id);
        if(toManyNode!=null){
            tikTokTask.onTaskErr("注册被风控，提示访问太频繁！");
            return;
        }
        allowSystemPermission();
        AccessibilityNodeInfo jumpBt = findNodeFirstById(FindIdResouresConfig.register_jump_bt_id);
        //密码规则按钮
        AccessibilityNodeInfo regSetNickName1 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt1_id);
        AccessibilityNodeInfo regSetNickName2 = findNodeFirstById(FindIdResouresConfig.register_set_nickName_bt2_bt_id);
        if (jumpBt != null && regSetNickName1 != null && regSetNickName2 != null) {
            clickXy(jumpBt);
            TsUtils.showTips("跳过设置昵称");
            Thread.sleep(2000);
            List<AccessibilityNodeInfo> notAllowBtNode = findNodesByText("不允许");
            if (isNodeExist(notAllowBtNode)) {
                clickXy(notAllowBtNode.get(0));
                Thread.sleep(1000);
            }
            Thread.sleep(2000);
            jumpBt = findNodeFirstById(FindIdResouresConfig.register_jump_bt_id);
            if (jumpBt != null) {
                clickXy(jumpBt);
                Thread.sleep(2000);
            }
            tikTokTask.showLogAndTsPrint("注册成功：" + accountPhoneOrEmail);
            getCurrentAccountAndSendToServer(0,accountPhoneOrEmail);
//            Thread.sleep(2000);
//            tikTokTask.onTaskFinish();
        } else {
            List<AccessibilityNodeInfo> seekBarNodes = AccessibilityTool.getInstance().findNodesByIdPlus(null, null, service, FindIdResouresConfig.verifyImageCodeSwipeTypeForceNodeId);
            if (MyUtils.isEmpty(seekBarNodes)) {
                if (tryJumpTimes >= 2) {
                    tikTokTask.onTaskErr("无法跳过允许通讯录权限");
                    return;
                }
                TsUtils.showTips("尝试允许通讯录权限");
                int x = ScreenUtils.getAppScreenWidth() / 2;
                int y = 720;
                AccessibilityTool.getInstance().clickScreen(service, x, y);
                Thread.sleep(2000);
                y = 650;
                AccessibilityTool.getInstance().clickScreen(service, x, y);
                tryJumpTimes++;
                Thread.sleep(4000);
                dealWithRegisterSuccess(accountPhoneOrEmail, isSwipeType, finalTryTimes, tryJumpTimes);
            } else {
                toManyNode = findNodeFirstById(FindIdResouresConfig.request_to_many_text_id);
                if (toManyNode != null) {
                    tikTokTask.onTaskErr("账号被风控，注册失败");
                    return;
                }
                if (finalTryTimes < maxVerifyCodeTryTime) {
                    finalTryTimes++;
                    tikTokTask.showLogAndTsPrint("验证失败了，重试第" + finalTryTimes + "次");
                    AccessibilityNodeInfo refreshBt = findNodeFirstById(FindIdResouresConfig.refreshBtNodeId);
                    if (refreshBt != null) {
                        clickXy(refreshBt);
                        Thread.sleep(2000);
                    }
                    Thread.sleep(2000);
                    swipeSeekBar(accountPhoneOrEmail, isSwipeType, finalTryTimes);
                } else {
                    tikTokTask.onTaskErr("当前账号注册失败");
                }
            }
        }
    }


    /**
     * 获取当前账号信息并上传到服务器
     */
    public void getCurrentAccountAndSendToServer(int times, String email) throws InterruptedException {
        tikTokTask.showLogAndTsPrint("上传当前账号信息到服务器");
        tikTokTask.checkAndSendMessageToServer();
        if (isFirstInTikTokAndInSelectTagAc()) {
            //在选择tag页面
            if (isEnterInStartLookNextPage()) {
                //成功进入了tiktok主页面了
               tikTokTask.showLogAndTsPrint("进入了主页面");
            }
        }

        tikTokTask.showLogAndTsPrint("检测当前在哪个页面");
        if(checkIsInPersonalPage()){
            tikTokTask.showLogAndTsPrint("已在个人信息页");
            AccessibilityNodeInfo changeBtId = findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
            if (changeBtId != null) {
                tikTokTask.showLogAndTsPrint("已找到切换账号按钮");
                try {
                    String nickName=getNickName();
                    tikTokTask.showLogAndTsPrint("昵称已获取");
                    //获取用户名
                    String userName = getUserName();
                    tikTokTask.showLogAndTsPrint("用户名已获取");
                    //获取粉丝数
                    String fanCount = getUserFanCount();
                    tikTokTask.showLogAndTsPrint("粉丝数已获取");
                    //获取关注数
                    String attentionCount = getUserAttentionCount();
                    tikTokTask.showLogAndTsPrint("关注数已获取");
                    //获取点赞数
                    String likeCount = getUserLikeCount();
                    tikTokTask.showLogAndTsPrint("喜欢数已获取");
                    //获取用户签名
                    String signText = getSignText();
                    if(!MyUtils.isEmpty(nickName)&&nickName.equals("12")){
                        nickName="";
                    }
                    if(!MyUtils.isEmpty(userName)){
                        userName="";
                    }
                    if(!MyUtils.isEmpty(likeCount)){
                        likeCount="0";
                    }
                    if(!MyUtils.isEmpty(attentionCount)){
                        attentionCount="0";
                    }
                    if(!MyUtils.isEmpty(fanCount)){
                        fanCount="0";
                    }
                    tikTokTask.showLogAndTsPrint("点击切换账号按钮:"+userName);
                    if(Constants.isServiceApplication) {
                        AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                        Thread.sleep(2000);
                        List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                        if(!isNodeExist(accountsNode)){
                            clickXy(changeBtId);
                            Thread.sleep(2000);
                        }
                    }else{
                        clickXy(changeBtId);
                        Thread.sleep(3000);
                    }
                    List<String> accountList = new ArrayList<>();
                    for(int swipeTime=0;swipeTime<2;swipeTime++) {
                        List<AccessibilityNodeInfo> accountsNode = findNodesById(FindIdResouresConfig.accountListTextId);
                        if (isNodeExist(accountsNode)) {
                            String lastText=accountsNode.get(accountsNode.size()-1).getText().toString();
                            int maxFor=accountsNode.size();
                            if("添加账号".equals(lastText)){
                                maxFor=accountsNode.size()-1;
                            }
                            for (int i = 0; i < maxFor; i++) {
                                String account = accountsNode.get(i).getText().toString();
                                if (account.startsWith("@")) {
                                    account = account.substring(1);
                                }
                                boolean isAccountHasInList=false;
                                for(String accInList:accountList){
                                    if(accInList.equals(account)){
                                        isAccountHasInList=true;
                                        break;
                                    }
                                }
                                if (!MyUtils.isEmpty(account)&&!isAccountHasInList) {
                                    accountList.add(account);
                                }
                            }
                        }
                        if(accountList.size()>=4){
                            swipe(ScreenUtils.getAppScreenWidth()/2,1212,ScreenUtils.getAppScreenWidth()/2,880,600);
                        }
                    }
                    if(!MyUtils.isEmpty(accountList)) {
                        tikTokTask.showLogAndTsPrint("获取账号成功"+accountList.get(0));
                        Thread.sleep(1000);
                        tikTokTask.serverTaskDataBean.setAccountId(accountList.get(0));
                        tikTokTask.serverTaskDataBean.setNickName(nickName);
                        tikTokTask.serverTaskDataBean.setFans(Integer.parseInt(fanCount));
                        tikTokTask.serverTaskDataBean.setAttention(Integer.parseInt(attentionCount));
                        tikTokTask.serverTaskDataBean.setLike(Integer.parseInt(likeCount));
                        tikTokTask.serverTaskDataBean.setProfile(signText);
                    }else{
                        tikTokTask.showLogAndTsPrint("获取账号失败");
                    }
                    tikTokTask.onTaskFinish();
                } catch (InterruptedException e) {
                    if(times>=6){
                        tikTokTask.onTaskErr("无法获取账号信息");
                        return;
                    }
                    Thread.sleep(2000);
                    times++;
                    getCurrentAccountAndSendToServer(times, email);
                }
            }else {
                tikTokTask.showLogAndTsPrint("未找到切换账号按钮");
                if(times>=6){
                    tikTokTask.onTaskErr("无法获取账号信息");
                    return;
                }
                Thread.sleep(2000);
                times++;
                getCurrentAccountAndSendToServer(times, email);
            }
        }else{
            tikTokTask.showLogAndTsPrint("不在个人信息页");
            if(checkCurrentPageIsMainPage()){
                tikTokTask.showLogAndTsPrint("已在tiktok首页");
                AccessibilityNodeInfo nodes = findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
                if (nodes != null) {
                    clickXy(nodes);
                    Thread.sleep(3000);
                    getCurrentAccountAndSendToServer(times, email);
                    return;
                } else {
                    tikTokTask.showLogAndTsPrint("未找到底部主页按钮");
                }
                Thread.sleep(3000);
                if(times>=6){
                    tikTokTask.onTaskErr("无法获取账号信息");
                    return;
                }
                times++;
                getCurrentAccountAndSendToServer(times, email);
            }else{
                if(times>=6||tikTokTask.taskStatus==TikTokTask.ERR){
                    tikTokTask.onTaskErr("无法获取账号信息");
                    return;
                }
                backOnce();
                Thread.sleep(3000);
                times++;
                getCurrentAccountAndSendToServer(times, email);
            }

        }
    }


    private void getPhoneCode(OnVerifyCodeGetListener onVerifyCodeGetListener) throws InterruptedException {
        if(onVerifyCodeGetListener!=null){
            onVerifyCodeGetListener.onVerifyCodeGet("345213");
        }
    }

    private boolean dealWithImageVerify(int registerType) throws InterruptedException {
        boolean isDealSuccess=true;
        tikTokTask.showLogAndTsPrint("开始处理图形验证码");
        Thread.sleep(3000);
        return isDealSuccess;
    }


    /**
     * 这里处理手机区号相关选择操作
     */
    private void dealWithFrontCode() {
        AccessibilityNodeInfo frontText = findNodeFirstById(FindIdResouresConfig.register_phone_front_text_NodeId);
        if(frontText!=null&&frontText.getText()!=null){
            String frontTextStr=frontText.getText().toString();
            if(frontTextStr.equals(frontTextStr)){
                //区号相同不需要重新选择
            }
            //目前不关注区号直接进行注册

        }
    }


    //向上滑动
    public void swipeYearScrollBarToBottom(AccessibilityNodeInfo needScrollNode, int count,long duration){
        Rect rect = new Rect();
        needScrollNode.getBoundsInScreen(rect);
        float left = rect.left;
        float right = rect.right;
        float top = rect.top;
        float bottom = rect.bottom;
        int x = (int) ((left + right) / 2);
        int y = (int) ((top + bottom) / 2);
        if(y<0){
            y= (int) (Math.abs(top-bottom)*2);
        }
        int startY= (int) top;
        int endY= (int) bottom;
        int startX= x;
        int endX= x;
        LogUtils.v("startY=" + startY + ",endY=" + endY + ",startX=" + startX + ",endX=" + endX);
        swipe(startX, startY, endX, endY, 700);
        try {
            Thread.sleep(duration);
            count--;
            if (count > 0) {
                swipeYearScrollBarToBottom(needScrollNode,count,duration);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }



        /**
         * 获取首页搜索图标的节点
         */
        public AccessibilityNodeInfo getMainSearchIconNode () {
            AccessibilityNodeInfo imageNode = null;
            //开始搜索
            AccessibilityNodeInfo topBarLayoutGroupNode = findNodeFirstById(FindIdResouresConfig.topBarLayoutGroupId);
            //首页的搜索按钮可能存在两种情况
            if (topBarLayoutGroupNode != null && topBarLayoutGroupNode.getChildCount() > 0) {
                imageNode = topBarLayoutGroupNode.getChild(topBarLayoutGroupNode.getChildCount() - 1);
            } else {
                AccessibilityNodeInfo searchImgNode = findNodeFirstById(FindIdResouresConfig.mainSearchId);
                if (searchImgNode != null) {
                    imageNode = searchImgNode;
                }
            }
            return imageNode;
        }


        /**
         * 获取用户粉丝列表
         */
        public void getUserFanList (String userName) throws InterruptedException {
            if(tikTokTask==null||tikTokTask.taskStatus==BaseTask.STOP){
                return;
            }
            if (checkCurrentPageIsMainPage()) {
                AccessibilityNodeInfo imageNode = getMainSearchIconNode();
                if (imageNode != null) {
                    click(imageNode);
                    Thread.sleep(2000);
                    tikTokTask.showLogAndTsPrint("进入搜索页面");
                    AccessibilityNodeInfo searchEtNode = findNodeFirstById(FindIdResouresConfig.searchEtId);
                    if (searchEtNode != null) {
                        setNodeText(searchEtNode, userName);
                        Thread.sleep(2000);
                        AccessibilityNodeInfo searchBtNode = findNodeFirstById(FindIdResouresConfig.searchBtId);
                        if (searchBtNode != null) {
                            clickXy(searchBtNode);
                            tikTokTask.showLogAndTsPrint("搜索关键字");
                            Thread.sleep(8000);
                            AccessibilityNodeInfo topNode = findNodeFirstById(FindIdResouresConfig.searchPagePersonGroupId);
                            AccessibilityNodeInfo attentionNode = findNodeFirstById(FindIdResouresConfig.searchPagePersonHeadBtId);
                            if (topNode != null && attentionNode != null) {
                                clickXy(attentionNode);
                                tikTokTask.showLogAndTsPrint("已进入用户主页");
                                Thread.sleep(2000);
                                AccessibilityNodeInfo fanCountBtNode = findNodeFirstById(FindIdResouresConfig.otherFanCountBtId);
                                if (fanCountBtNode != null) {
                                    List<PersonInfo> personInfos = new ArrayList<>();
                                    String count = fanCountBtNode.getText().toString();
                                    if (MyUtils.isEmpty(count)) {
                                        tikTokTask.onTaskErr("获取粉丝信息失败");
                                        return;
                                    }
                                    int maxFanCount = 10000;
                                    if (!count.contains(".")) {
                                        maxFanCount = Integer.parseInt(count);
                                    }
                                    tikTokTask.showLogAndTsPrint("用户粉丝:" + count);
                                    if ("0".contentEquals(fanCountBtNode.getText())) {
                                        tikTokTask.showLogAndTsPrint("用户没有粉丝");
                                        Thread.sleep(1000);
                                        tikTokTask.onTaskFinish();
                                        //TODO 可能需要传给服务器对应的信息
                                        sendMsgToServer(personInfos);
                                    } else {
                                        clickXy(fanCountBtNode);
                                        tikTokTask.showLogAndTsPrint("已进入粉丝列表页");
                                        Thread.sleep(6000);
                                        for (int j = 0; j < 50; j++) {
                                            AccessibilityNodeInfo fanRecycleViewNode = findNodeFirstById(FindIdResouresConfig.fanRecycleViewIdBtId);
                                            if (fanRecycleViewNode != null && fanRecycleViewNode.getChildCount() > 0) {
                                                for (int i = 0; i < fanRecycleViewNode.getChildCount(); i++) {
                                                    AccessibilityNodeInfo fanUserNameNode = findNodeFirstById(fanRecycleViewNode.getChild(i), FindIdResouresConfig.fanUserNameBtId);
                                                    AccessibilityNodeInfo fanNickNameNode = findNodeFirstById(fanRecycleViewNode.getChild(i), FindIdResouresConfig.fanNickNameBtId);
                                                    AccessibilityNodeInfo fanIsAttentionNode = findNodeFirstById(fanRecycleViewNode.getChild(i), FindIdResouresConfig.fanIsAttentionBtId);
                                                    if (fanIsAttentionNode != null && fanUserNameNode != null && fanNickNameNode != null) {
                                                        LogUtils.i("用户名：" + fanUserNameNode.getText());
                                                        LogUtils.i("昵称：" + fanNickNameNode.getText());
                                                        LogUtils.i("是否关注：" + fanIsAttentionNode.getText());
                                                        LogUtils.w("---------------------------------------");
                                                        PersonInfo personInfo = new PersonInfo();
                                                        CharSequence userNameStr = fanUserNameNode.getText();
                                                        if (userNameStr != null) {
                                                            personInfo.setUserName(String.valueOf(userNameStr));
                                                        }
                                                        CharSequence isAttentionNodeText = fanIsAttentionNode.getText();
                                                        if (isAttentionNodeText != null) {
                                                            personInfo.setAttentionText(String.valueOf(isAttentionNodeText));
                                                        }
                                                        CharSequence nickNameNodeText = fanNickNameNode.getText();
                                                        if (nickNameNodeText != null) {
                                                            personInfo.setNickName(String.valueOf(nickNameNodeText));
                                                        }
                                                        boolean isListContains = false;
                                                        for (PersonInfo p : personInfos) {
                                                            if (p.equals(personInfo)) {
                                                                isListContains = true;
                                                                break;
                                                            }
                                                        }
                                                        if (!isListContains) {
                                                            personInfos.add(personInfo);
                                                        }
                                                        if (personInfos.size() >= maxFanCount) {
                                                            break;
                                                        }
                                                        if(tikTokTask.currentTaskType== TaskTypeConfig.TIKTOK_TASK_GET_USER_FAN_LIST&&tikTokTask.serverTaskDataBean.getMaxFollowCount()>0) {
                                                            if (personInfos.size() >= tikTokTask.serverTaskDataBean.getMaxFollowCount()) {
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                                if (personInfos.size() < maxFanCount && personInfos.size() < tikTokTask.serverTaskDataBean.getMaxFollowCount()) {
                                                    swipeYearScrollBarToBottom(1);
                                                } else {
                                                    break;
                                                }
                                            } else {
                                                break;
                                            }
                                        }
                                        if (MyUtils.isEmpty(personInfos)) {
                                            Thread.sleep(1000);
                                            tikTokTask.onTaskErr("用户的粉丝列表数据获取失败");
                                        } else {
                                            tikTokTask.showLogAndTsPrint("原始的数据："+personInfos.size()+"条");
                                            if (personInfos.size() >= tikTokTask.serverTaskDataBean.getMaxFollowCount()&&tikTokTask.serverTaskDataBean.getMaxFollowCount()>0) {
                                                personInfos = personInfos.subList(0, tikTokTask.serverTaskDataBean.getMaxFollowCount());
                                            }
                                            LogUtils.w(">>>粉丝共计获取到：" + personInfos.size() + "个<<<");
                                            tikTokTask.showLogAndTsPrint("获取到" + personInfos.size() + "个粉丝数据");
                                            sendMsgToServer(personInfos);
                                            Thread.sleep(3000);
                                            tikTokTask.onTaskFinish();
                                        }
                                    }
                                } else {
                                    Thread.sleep(1000);
                                    tikTokTask.changeTaskStatusToStart();
                                }
                            } else {
                                tikTokTask.showLogAndTsPrint("未找到此用户名信息，任务结束");
                                Thread.sleep(1000);
                                tikTokTask.onTaskFinish();
                            }
                        } else {
                            Thread.sleep(1000);
                            tikTokTask.changeTaskStatusToStart();
                        }
                    } else {
                        Thread.sleep(1000);
                        tikTokTask.changeTaskStatusToStart();
                    }
                } else {
                    Thread.sleep(1000);
                    tikTokTask.changeTaskStatusToStart();
                }
            } else {
                tikTokTask.showLogAndTsPrint("不在首页，点击返回按钮");
                backOnce();
                Thread.sleep(2000);
                tikTokTask.changeTaskStatusToStart();
            }

        }


        //将粉丝用户数据返回给服务端
        private void sendMsgToServer (List < PersonInfo > personInfos) {
            MsgTaskBean msgTaskBean = new MsgTaskBean();
            msgTaskBean.setTaskType(tikTokTask.currentTaskType);
            msgTaskBean.setType(3);
            msgTaskBean.setCode(1003);
            msgTaskBean.setToken(SPUtils.getInstance().getString("token"));
            List<String> accounts = new ArrayList<>();
            if (!MyUtils.isEmpty(personInfos)) {
                for (int i = 0; i < personInfos.size(); i++) {
                    accounts.add(personInfos.get(i).getUserName());
                }
            }
            AccountsListObject accountsListObject = new AccountsListObject();
            accountsListObject.getAccounts().addAll(accounts);
            ServerInnerDataBean serverInnerDataBean = new ServerInnerDataBean();
            serverInnerDataBean.setJson(GsonUtils.toJson(accountsListObject));
            serverInnerDataBean.setId(tikTokTask.serverTaskDataBean.getId());
            serverInnerDataBean.setMainId(tikTokTask.serverTaskDataBean.getMainId());
            msgTaskBean.setData(serverInnerDataBean);
            WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(msgTaskBean));
        }


        /**
         * 修改个人资料
         *
         * @param nickName
         * @param signText
         * @param fileDirPath
         */
        public void changePersonalInfo (String nickName, String signText, String fileDirPath) throws
        InterruptedException {
            String fileDirName = fileDirPath;
            if (!MyUtils.isEmpty(fileDirPath)) {
                if (fileDirPath.contains("/")) {
                    fileDirName = fileDirPath.substring(fileDirPath.lastIndexOf("/") + 1);
                }
            }
            //检测是否在个人中心页面
            if (checkIsInPersonalPage()) {
                AccessibilityNodeInfo editInfoBtNode = findNodeFirstById(FindIdResouresConfig.personalEditBtId);
                if (editInfoBtNode == null) {
                    backToTiktokMainPage();
                } else {
                    String finalFileDirName = fileDirName;
                    clickXy(editInfoBtNode);
                    tikTokTask.showLogAndTsPrint("点击进入资料编辑页");
                    Thread.sleep(2000);
                    AccessibilityNodeInfo nickNameBtNode = findNodeFirstById(FindIdResouresConfig.personalEditNickNameBtId);
                    if (nickNameBtNode != null) {
                        //进入编辑资料页面成功
                        if (!MyUtils.isEmpty(nickName)) {
                            boolean isNickNameEditSuccess = changeNickName(nickNameBtNode, nickName, signText);
                            if (!isNickNameEditSuccess) {
                                return;
                            }
                        }

                        //防止退回到个人中心页面
                        if (checkIsInPersonalPage()) {
                             editInfoBtNode = findNodeFirstById(FindIdResouresConfig.personalEditBtId);
                             if(editInfoBtNode!=null){
                                 clickXy(editInfoBtNode);
                                 Thread.sleep(3000);
                             }
                        }
                        //进入个性签名页面编辑签名简介
                        if (!MyUtils.isEmpty(signText)) {
                            boolean isSignTextEditSuccess = changeSignText(signText);
                            if (!isSignTextEditSuccess) {
                                return;
                            }
                        }

                        //防止退回到个人中心页面
                        if (checkIsInPersonalPage()) {
                            editInfoBtNode = findNodeFirstById(FindIdResouresConfig.personalEditBtId);
                            if(editInfoBtNode!=null){
                                clickXy(editInfoBtNode);
                                Thread.sleep(3000);
                            }
                        }

                        //修改头像
                        if (!MyUtils.isEmpty(finalFileDirName)) {
                            boolean isImageHeadEditSuccess = changeImageHead(finalFileDirName);
                            if (!isImageHeadEditSuccess) {
                                return;
                            }
                            deleteFilePath(new File(fileDirPath));
                        }
                        tikTokTask.onTaskFinish();
                    } else {
                        backToTiktokMainPage();
                    }
                }
            } else {
                if (checkCurrentPageIsMainPage()) {
                    LogUtils.w("回到首页成功");
                    boolean isLogin = checkMainPageTabSize();
                    if (isLogin) {
                        AccessibilityNodeInfo node = findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
                        if (node != null) {
                            try {
                                clickXy(node);
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            tikTokTask.showLogAndTsPrint("未找到底部主页按钮");
                        }
                        tikTokTask.changeTaskStatusToStart();
                    } else {
                        tikTokTask.showLogAndTsPrint("未登录状态下无法修改资料");
                        tikTokTask.onTaskErr("未登录状态下无法修改资料");
                    }
                } else {
                    backToTiktokMainPage();
                }
            }
        }


    /**
     * 任务做完后删除文件夹
     * @param folder
     */
    public  void deleteFilePath(File folder) {
        if (folder != null && folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFilePath(file); // 递归删除子文件夹
                    } else {
                        file.delete(); // 删除文件
                    }
                }
            }
            folder.delete(); // 删除空文件夹
        } else {
            if (folder != null && folder.exists()){
                if(folder.isFile()){
                    folder.delete(); // 删除文件
                    return;
                }
            }
            // 文件夹不存在或者不是目录，做相应处理
            System.out.println("Folder does not exist or is not a directory");
            tikTokTask.showLogAndTsPrint("删除文件夹失败");
        }
        //刷新相册
        new MediaRefreshHelper(BaseApp.app).scanFolder(folder);
    }




        private boolean changeSignText (String signText) throws InterruptedException {
            boolean isSignTextEditSuccess = false;
            Thread.sleep(2000);
            //这里是编辑个人简介的逻辑
            AccessibilityNodeInfo signBtTextNode = findNodeFirstById(FindIdResouresConfig.personalEditSignTextBtId);
            if (signBtTextNode != null) {
                clickXy(signBtTextNode);
                tikTokTask.showLogAndTsPrint("进入编辑简介页面");
                Thread.sleep(2000);
                signBtTextNode = findNodeFirstById(FindIdResouresConfig.personalEditSignTextBtId);
                if (signBtTextNode != null) {
                    clickXy(signBtTextNode);
                    tikTokTask.showLogAndTsPrint("进入编辑简介页面");
                    Thread.sleep(2000);
                }
                AccessibilityNodeInfo editSignTextNode = findNodeFirstById(FindIdResouresConfig.personalEditNickNameInnerBtId);
                if (editSignTextNode != null) {
                    setNodeText(editSignTextNode, signText);
                    tikTokTask.showLogAndTsPrint("设置新简介");
                    Thread.sleep(2000);
                    AccessibilityNodeInfo signTextSaveBtNode = findNodeFirstById(FindIdResouresConfig.personalNickNameSaveInnerBtId);
                    if (signTextSaveBtNode != null) {
                        clickXy(signTextSaveBtNode);
                        tikTokTask.showLogAndTsPrint("保存简介");
                        Thread.sleep(6000);
                        AccessibilityNodeInfo personalPageNickNameItemNode = findNodeFirstById(FindIdResouresConfig.personalEditNickNameBtId);
                        if (personalPageNickNameItemNode == null) {
                            backOnce();
                            Thread.sleep(2000);
                        }
                        isSignTextEditSuccess = true;
                    } else {
                        Thread.sleep(2000);
                        tikTokTask.onTaskErr("无法保存简介");
                    }
                } else {
                    Thread.sleep(2000);
                    tikTokTask.onTaskErr("无法输入新简介");
                }
            } else {
                Thread.sleep(2000);
                tikTokTask.onTaskErr("无法进入简介编辑页");
            }
            return isSignTextEditSuccess;
        }

        private boolean changeImageHead (String fileDirName) throws InterruptedException {
            boolean isImageHeadEditSuccess = false;
            AccessibilityNodeInfo changeUserImageHead = findNodeFirstById(FindIdResouresConfig.personalEditUserHeadImageId);
            if (changeUserImageHead != null) {
                clickXy(changeUserImageHead);
                Thread.sleep(3000);
                //检测是否存在权限允许弹框
                allowSystemPermission();
                List<AccessibilityNodeInfo> selectImageItems = findNodesById(FindIdResouresConfig.personalSelectUserHeadTypeItemId);
                if (isNodeExist(selectImageItems) && selectImageItems.size() >= 2) {
                    clickXy(selectImageItems.get(1));
                    Thread.sleep(3000);
                    //检测是否存在权限允许弹框
                    allowSystemPermission();
                    return selectImageToChangeHeadPic(fileDirName,0);
                } else {
                    Thread.sleep(2000);
                    tikTokTask.onTaskErr("无法进入图片选择页");
                }
            } else {
                Thread.sleep(2000);
                tikTokTask.onTaskErr("无法进入图片选择页");
            }
            return isImageHeadEditSuccess;
        }

    private boolean selectImageToChangeHeadPic(String fileDirName,int tryTime) throws InterruptedException {
        boolean isImageHeadEditSuccess=false;
        AccessibilityNodeInfo imgDirSelectedNode = findNodeFirstById(FindIdResouresConfig.imageDirSelectedBtId);
        if (imgDirSelectedNode != null) {
            clickXy(imgDirSelectedNode);
            Thread.sleep(2000);
            List<AccessibilityNodeInfo> imgDirNodes = findNodesById(FindIdResouresConfig.imageDirNameTextId);
            if (isNodeExist(imgDirNodes)) {
                AccessibilityNodeInfo needChooseDir = null;
                for (int j = 0; j < 5; j++) {
                    for (int i = 0; i < imgDirNodes.size(); i++) {
                        CharSequence dirName = imgDirNodes.get(i).getText();
                        if (fileDirName.contentEquals(dirName)) {
                            tikTokTask.showLogAndTsPrint("找到目标文件夹：" + dirName);
                            Thread.sleep(3000);
                            imgDirNodes = findNodesById(FindIdResouresConfig.imageDirNameTextId);
                            if (isNodeExist(imgDirNodes) && imgDirNodes.size() > i) {
                                needChooseDir = imgDirNodes.get(i);
                                break;
                            }
                        }
                    }
                    if (needChooseDir != null) {
                        break;
                    } else {
                        LogUtils.i("没找到对应文件夹，滑动一次");
                        AccessibilityNodeInfo relativeNode = imgDirNodes.get(0).getParent();
                        if (relativeNode != null) {
                            AccessibilityNodeInfo listViewNode = relativeNode.getParent();
                            if (listViewNode != null) {
                                swipeNodeInfo(1, listViewNode);
                            } else {
                                swipe(340, 950, 345, 440, 700);
                                Thread.sleep(2000);
                            }
                        } else {
                            swipe(340, 950, 345, 440, 700);
                            Thread.sleep(2000);
                        }
                        imgDirNodes = findNodesById(FindIdResouresConfig.imageDirNameTextId);
                    }
                }
                if (needChooseDir != null) {
                    clickXy(needChooseDir.getParent());
                    tikTokTask.showLogAndTsPrint("进入对应文件夹");
                    Thread.sleep(2000);
                    AccessibilityNodeInfo imageSelectTopCheckBoxIdNode = findNodeFirstById(FindIdResouresConfig.imageSelectTopCheckBoxId);
                    if (imageSelectTopCheckBoxIdNode != null) {
                        clickXy(imageSelectTopCheckBoxIdNode);
                        Thread.sleep(2000);
                        AccessibilityNodeInfo imageSureBottomNode = findNodeFirstById(FindIdResouresConfig.imageSelectBottomSureId);
                        if (imageSureBottomNode != null) {
                            clickXy(imageSureBottomNode);
                            Thread.sleep(2000);
                            AccessibilityNodeInfo checkBoxNode = findNodeFirstById(FindIdResouresConfig.saveAndPublishCheckBoxId);
                            AccessibilityNodeInfo bottomSaveBtNode = findNodeFirstById(FindIdResouresConfig.saveImageHeadBtNodeId);
                            if (checkBoxNode != null && bottomSaveBtNode != null) {
                                if (checkBoxNode.isChecked()) {
                                    clickXy(checkBoxNode);
                                    Thread.sleep(2000);
                                }
                                clickXy(bottomSaveBtNode);
                                Thread.sleep(5000);

                                bottomSaveBtNode = findNodeFirstById(FindIdResouresConfig.saveImageHeadBtNodeId);
                                if (bottomSaveBtNode != null) {
                                    LogUtils.i("还未上传成功，重试一次");
                                    if (checkBoxNode.isChecked()) {
                                        clickXy(checkBoxNode);
                                        Thread.sleep(2000);
                                    }
                                    clickXy(bottomSaveBtNode);
                                    Thread.sleep(5000);
                                }
                                tikTokTask.showLogAndTsPrint("图片选择完成");
                                Thread.sleep(3000);
                                tikTokTask.onTaskFinish();
                                AccessibilityNodeInfo personalPageNickNameItemNode = findNodeFirstById(FindIdResouresConfig.personalEditNickNameBtId);
                                if (personalPageNickNameItemNode == null) {
                                    backOnce();
                                    Thread.sleep(2000);
                                }
                                isImageHeadEditSuccess = true;
                            } else {
                                tikTokTask.onTaskErr("无法保存上传图片");
                            }
                        } else {
                            tikTokTask.onTaskErr("无法确定已选图片");
                        }
                    } else {
                        tikTokTask.onTaskErr("无法勾选图片");
                    }
                } else {
                    tikTokTask.onTaskErr("找不到文件夹名称:" + fileDirName);
                }
            } else {
                Thread.sleep(2000);
                tikTokTask.onTaskErr("找不到文件夹名称:" + fileDirName);
            }
        } else {
            if(tryTime==0) {
                int x = ScreenUtils.getAppScreenWidth() / 2;
                AccessibilityTool.getInstance().clickScreen(service, x, 740);
                tikTokTask.showLogAndTsPrint("允许媒体读取权限");
                Thread.sleep(2000);
                return selectImageToChangeHeadPic(fileDirName,1);
            }else {
                tikTokTask.onTaskErr("选择文件夹失败");
            }
        }
        return isImageHeadEditSuccess;
    }


    /**
         * 修改昵称和简介
         *
         * @param nickNameBtNode
         * @param nickName
         * @param signText
         * @throws InterruptedException
         */
        private boolean changeNickName (AccessibilityNodeInfo nickNameBtNode, String
        nickName, String signText) throws InterruptedException {
            boolean isNickNameEditSuccess = false;
            clickXy(nickNameBtNode);
            tikTokTask.showLogAndTsPrint("进入编辑昵称页面");
            //这里是编辑昵称的逻辑
            Thread.sleep(2000);
            AccessibilityNodeInfo editNickNameNode = findNodeFirstById(FindIdResouresConfig.personalEditNickNameInnerBtId);
            if (editNickNameNode != null) {
                setNodeText(editNickNameNode, nickName);
                tikTokTask.showLogAndTsPrint("设置新昵称");
                Thread.sleep(2000);
                AccessibilityNodeInfo nickNameSaveBtNode = findNodeFirstById(FindIdResouresConfig.personalNickNameSaveInnerBtId);
                if (nickNameSaveBtNode != null) {
                    clickXy(nickNameSaveBtNode);
                    tikTokTask.showLogAndTsPrint("保存新昵称");
                    Thread.sleep(6000);
                    AccessibilityNodeInfo sureDialogBtNode = findNodeFirstById(FindIdResouresConfig.personalNickNameSaveSureDialogBtId);
                    if (sureDialogBtNode != null && sureDialogBtNode.getChildCount() > 0) {
                        if (sureDialogBtNode.getChildCount() == 1) {
                            if (sureDialogBtNode.getChild(0).getChildCount() == 2) {
                                clickXy(sureDialogBtNode.getChild(0).getChild(1));
                                LogUtils.i("点击二次确认的弹框保存");
                                Thread.sleep(6000);
                            }
                        } else if (sureDialogBtNode.getChildCount() == 2) {
                            clickXy(sureDialogBtNode.getChild(0));
                            LogUtils.i("点击二次确认的弹框保存");
                            Thread.sleep(6000);
                        }
                    }
                    AccessibilityNodeInfo personalPageNickNameItemNode = findNodeFirstById(FindIdResouresConfig.personalEditNickNameBtId);
                    if (personalPageNickNameItemNode == null) {
                        backOnce();
                        Thread.sleep(2000);
                    }
                    tikTokTask.showLogAndTsPrint("昵称保存完成");
                    isNickNameEditSuccess = true;
                } else {
                    Thread.sleep(2000);
                    tikTokTask.onTaskErr("昵称无法保存");
                }
            } else {
                Thread.sleep(2000);
                tikTokTask.onTaskErr("新昵称无法输入");
            }
            return isNickNameEditSuccess;
        }


        /**
         * 自动发布作品
         *
         * @param fileDirName  发布的视频的文件夹名称
         * @param publishTitle 发布视频的标题
         */
        public void publishWorks (String fileDirName, String publishTitle) throws
        InterruptedException {
            //检测是否在首页
            if (checkCurrentPageIsMainPage()) {
                //点击进入发布页面
                if (enterInPublishAc()) {
                    //检测是否存在权限允许弹框
                    allowSystemPermission();
                    Thread.sleep(1000);
                    allowSystemPermission();
                    //点击进入选择作品页面
                    if (enterInPhotoChooseAc()) {
                        //检测是否存在权限允许弹框
                        allowSystemPermission();
                        Thread.sleep(1000);
                        allowSystemPermission();
                        //选择一个作品进行发布
                        if (chooseImageOrMp4File(fileDirName,0)) {
                            //进入发布作品编辑页面
                            if (enterInEditPublishAc()) {
                                //发布作品
                                if (publishWork(publishTitle)) {
                                    deleteFilePath(new File(fileDirName));
                                    tikTokTask.onTaskFinish();
                                }
                            }
                        }
                    }
                }
            } else {
                //返回到首页
                backToTiktokMainPage();
            }
        }


        /**
         * 根据文件夹选择对应需要发布的作品
         *
         * @param fileDirPath
         * @return
         * @throws InterruptedException
         */
        public boolean chooseImageOrMp4File (String fileDirPath,int tryTime) throws InterruptedException {
            boolean isStepSuccess = false;
            String fileDirName = fileDirPath;
            if (fileDirPath.contains("/")) {
                fileDirName = fileDirPath.substring(fileDirPath.lastIndexOf("/") + 1);
            }
            AccessibilityNodeInfo imgDirSelectedNode = findNodeFirstById(FindIdResouresConfig.selectDirBtInPublishAcBtId);
            if (imgDirSelectedNode != null) {
                clickXy(imgDirSelectedNode);
                Thread.sleep(2000);
                List<AccessibilityNodeInfo> imgDirNodes = findNodesById(FindIdResouresConfig.selectDirItemBtPublishAcBtId);
                if (isNodeExist(imgDirNodes)) {
                    AccessibilityNodeInfo needChooseDir = null;
                    for (int j = 0; j < 5; j++) {
                        for (int i = 0; i < imgDirNodes.size(); i++) {
                            CharSequence dirName = imgDirNodes.get(i).getText();
                            if (fileDirName.contentEquals(dirName)) {
                                needChooseDir = imgDirNodes.get(i);
                                break;
                            }
                        }
                        if (needChooseDir != null) {
                            break;
                        } else {
                            LogUtils.i("没找到对应文件夹，滑动一次");
                            AccessibilityNodeInfo relativeNode = imgDirNodes.get(0).getParent();
                            if (relativeNode != null) {
                                AccessibilityNodeInfo listViewNode = relativeNode.getParent();
                                if (listViewNode != null) {
                                    swipeNodeInfo(1, listViewNode);
                                } else {
                                    swipe(340, 950, 345, 440, 700);
                                    Thread.sleep(2000);
                                }
                            } else {
                                swipe(340, 950, 345, 440, 700);
                                Thread.sleep(2000);
                            }
                        }
                    }
                    if (needChooseDir != null) {
                        clickXy(needChooseDir);
                        tikTokTask.showLogAndTsPrint("进入对应文件夹");
                        Thread.sleep(2000);
                        AccessibilityNodeInfo imageSureBottomNode = findNodeFirstById(FindIdResouresConfig.publishAcImageOrMp4ItemId);
                        if (imageSureBottomNode != null) {
                            clickXy(imageSureBottomNode);
                            Thread.sleep(4000);
                            isStepSuccess = true;
                        } else {
                            tikTokTask.onTaskErr("无法选择图片或视频");
                        }
                    } else {
                        tikTokTask.onTaskErr("找不到对应文件夹:" + fileDirName);
                    }
                } else {
                    Thread.sleep(2000);
                    tikTokTask.onTaskErr("找不到对应文件夹:" + fileDirName);
                }
            } else {
                if(tryTime==0) {
                    int x = ScreenUtils.getAppScreenWidth() / 2;
                    AccessibilityTool.getInstance().clickScreen(service, x, 740);
                    tikTokTask.showLogAndTsPrint("允许媒体读取权限");
                    Thread.sleep(2000);
                    return chooseImageOrMp4File(fileDirName,1);
                }else {
                    Thread.sleep(2000);
                    tikTokTask.onTaskErr("无法切换文件夹");
                }
            }
            return isStepSuccess;
        }


        /**
         * 进入发布页面
         *
         * @return
         */
        private boolean enterInPublishAc () {
            boolean isStepSuccess = false;
            AccessibilityNodeInfo publishBt = findNodeFirstById(FindIdResouresConfig.publishVideoMainBtId);
            if (publishBt != null) {
                try {
                    clickXy(publishBt);
                    Thread.sleep(3000);
                    isStepSuccess = true;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                tikTokTask.onTaskErr("无法进入发布页面");
            }
            return isStepSuccess;
        }


        /**
         * 进入图片选择页面
         *
         * @return
         */
        private boolean enterInPhotoChooseAc () {
            boolean isStepSuccess = false;
            AccessibilityNodeInfo publishBt = findNodeFirstById(FindIdResouresConfig.selectBtInPublishAcBtId);
            if (publishBt != null) {
                try {
                    clickXy(publishBt);
                    Thread.sleep(2000);
                    isStepSuccess = true;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                tikTokTask.onTaskErr("无法进入图片选择页");
            }
            return isStepSuccess;
        }


        /**
         * 进入最后的编辑页面
         *
         * @return
         */
        private boolean enterInEditPublishAc () {
            boolean isStepSuccess = false;
            AccessibilityNodeInfo publishBt = findNodeFirstById(FindIdResouresConfig.publishToNextBtId);
            AccessibilityNodeInfo chooseMusicNextBtNode = findNodeFirstById(FindIdResouresConfig.publishAcChooseMusicNextId);
            try {
                if (publishBt != null) {
                    clickXy(publishBt);
                    isStepSuccess = true;
                    Thread.sleep(3000);
                } else {
                    if (chooseMusicNextBtNode != null) {
                        clickXy(chooseMusicNextBtNode);
                        isStepSuccess = true;
                        Thread.sleep(3000);
                    } else {
                        tikTokTask.onTaskErr("无法进入作品编辑详情页");
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return isStepSuccess;
        }


        /**
         * 编辑内容并发布
         *
         * @return
         */
        private boolean publishWork (String worksTitle) throws InterruptedException {
            boolean isStepSuccess = false;
            Thread.sleep(3000);
            //防止下一步按钮还存在
            AccessibilityNodeInfo chooseMusicNextBtNode = findNodeFirstById(FindIdResouresConfig.publishAcChooseMusicNextId);
            if (chooseMusicNextBtNode != null) {
                clickXy(chooseMusicNextBtNode);
                Thread.sleep(4000);
            }
            //防止底部弹个框起来
            AccessibilityNodeInfo bottomDialogNodeId = findNodeFirstById(FindIdResouresConfig.bottomDialogNodeId);
            AccessibilityNodeInfo bottomDialogNodeId2 = findNodeFirstById(FindIdResouresConfig.bottomDialogNodeId2);
            if(bottomDialogNodeId!=null){
                clickXy(bottomDialogNodeId);
                Thread.sleep(3000);
            }
            if(bottomDialogNodeId2!=null){
                clickXy(bottomDialogNodeId2);
                Thread.sleep(3000);
            }
            AccessibilityNodeInfo publishEtBt = findNodeFirstById(FindIdResouresConfig.publishEdiTextId);
            AccessibilityNodeInfo publishBt = findNodeFirstById(FindIdResouresConfig.publishBtId);
            if (!MyUtils.isEmpty(worksTitle) && publishEtBt != null) {
                setNodeText(publishEtBt, worksTitle);
                LogUtils.i("设置标题");
                Thread.sleep(4000);
            }
            if (publishBt != null) {
                try {
                    clickXy(publishBt);
                    Thread.sleep(4000);
                    isStepSuccess = true;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                tikTokTask.onTaskErr("发布作品失败");
            }
            return isStepSuccess;
        }


        public interface OnAttentionCommentOverListener {
            void onFinish(boolean isSuccess) throws InterruptedException;
        }

        /**
         * 被关注自动私信
         * @param replayText
         */
        public void autoReplayWhenBeAttention (ChatMsgList
        replayText, OnAttentionCommentOverListener onAttentionCommentOverListener) throws
        InterruptedException {
            if (checkCurrentPageIsMainPage()) {
                Thread.sleep(3000);
                boolean isEnterInMessageBoxPage = checkCurrentPageIsMessageBoxPage();
                //已进入首页
                if (isEnterInMessageBoxPage) {
                    Thread.sleep(2000);
                    tikTokTask.showLogAndTsPrint("进入收件箱页成功");
                    boolean isInFansListPage = enterInNewFanListPage();
                    //切换到收件箱页面
                    if (isInFansListPage) {
                        Thread.sleep(2000);
                        List<AccessibilityNodeInfo> listNewFanItemNode = findNodesById(FindIdResouresConfig.newFanListItemNodeId);
                        if (isNodeExist(listNewFanItemNode)) {
                            //已进入到新粉丝列表的消息页
                            enterInPersonDetailPage(replayText);
                            if (onAttentionCommentOverListener != null) {
                                onAttentionCommentOverListener.onFinish(true);
                            } else {
                                tikTokTask.onTaskFinish();
                            }
                        } else {
                            tikTokTask.onTaskErr("未获取到新粉丝消息");
                        }
                    } else {
                        tikTokTask.onTaskErr("未获取到新粉丝消息");
                    }
                }
            } else {
                backOnce();
                Thread.sleep(500);
                backOnce();
                Thread.sleep(500);
                backOnce();
                Thread.sleep(500);
                backOnce();
                Thread.sleep(1000);
                AppUtils.launchApp(Constants.tiktokPackageName);
                Thread.sleep(1000);
                tikTokTask.attentionAndReplayTask();
            }
        }


        /**
         * 进入到私信聊天页面
         * @return
         */
        private boolean enterInChatWithPersonPage () {
            boolean isStepSuccess = false;
            List<AccessibilityNodeInfo> chatWithPersonBts = findNodesById(FindIdResouresConfig.otherChatBtId);
            if (isNodeExist(chatWithPersonBts) && !chatWithPersonBts.isEmpty()) {
                try {
                    if (chatWithPersonBts.size() == 2 && chatWithPersonBts.get(0) != null) {
                        clickXy(chatWithPersonBts.get(0));
                        Thread.sleep(2000);
                        chatWithPersonBts = findNodesById(FindIdResouresConfig.otherChatBtId);
                        if (isNodeExist(chatWithPersonBts)) {
                            clickXy(chatWithPersonBts.get(0));
                            Thread.sleep(2000);
                            isStepSuccess = true;
                        }
                    } else {
                        clickXy(chatWithPersonBts.get(0));
                        Thread.sleep(2000);
                        isStepSuccess = true;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                tikTokTask.onTaskErr("无法进入私信页");
            }
            return isStepSuccess;
        }


        /**
         * 进入新粉丝消息通知页
         *
         * @return
         */
        private boolean enterInNewFanListPage () {
            boolean isStepSuccess = false;
            AccessibilityNodeInfo newFanItemBtNode = findNodeFirstById(FindIdResouresConfig.messageBoxNewFanBtId);
            if (newFanItemBtNode != null) {
                try {
                    clickXy(newFanItemBtNode);
                    Thread.sleep(3000);
                    isStepSuccess = true;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                tikTokTask.onTaskErr("无法进入新粉丝列表页");
            }
            return isStepSuccess;
        }


        /**
         * 分别进入粉丝个人信息页面并发送对应聊天内容
         *
         * @return
         */
        private boolean enterInPersonDetailPage (ChatMsgList chatContent) throws
        InterruptedException {
            int currentIndex = 0;
            boolean isStepSuccess = false;
            AccessibilityNodeInfo lookMoreNode = findNodeFirstById(FindIdResouresConfig.lookAllFanItemNodeId);
            if (lookMoreNode != null) {
                clickXy(lookMoreNode);
                Thread.sleep(2000);
            }
            for (int j = 0; j < 8; j++) {
                List<AccessibilityNodeInfo> listNewFanItemNode = findNodesById(FindIdResouresConfig.newFanListItemNodeId);
                if (isNodeExist(listNewFanItemNode)) {
                    for (int i = 0; i < listNewFanItemNode.size(); i++) {
                        AccessibilityNodeInfo newFanUserNode = listNewFanItemNode.get(i);
                        List<AccessibilityNodeInfo> dots = newFanUserNode.findAccessibilityNodeInfosByViewId(FindIdResouresConfig.newFanLeftDotId);
                        if (!isNodeExist(dots)) {
                            continue;
                        }
                        clickXy(newFanUserNode);
                        Thread.sleep(2000);
                        //点击进入个人中心页面
                        if (enterInChatWithPersonPage()) {
                            //防止底部弹个框起来
                            AccessibilityNodeInfo bottomDialogNodeId = findNodeFirstById(FindIdResouresConfig.bottomDialogNodeId);
                            if(bottomDialogNodeId!=null){
                                clickXy(bottomDialogNodeId);
                                Thread.sleep(4000);
                            }
                            //进入了聊天页面页面
                            AccessibilityNodeInfo chatWithOtherEtNodeId = findNodeFirstById(FindIdResouresConfig.otherChatBottomEtBtId);
                            if (chatWithOtherEtNodeId != null) {
                                setNodeText(chatWithOtherEtNodeId, chatContent.getPrivateMsgList().get(currentIndex));
                                if (currentIndex >= chatContent.getPrivateMsgList().size() - 1) {
                                    currentIndex = 0;
                                }
                                tikTokTask.showLogAndTsPrint("输入内容");
                                Thread.sleep(2000);
                                List<AccessibilityNodeInfo> chatWithOtherSendNodeIds = findNodesById(FindIdResouresConfig.attentionAndChatToUserBottomSendBtId);
                                if (isNodeExist(chatWithOtherSendNodeIds)) {
                                    int position=chatWithOtherSendNodeIds.size()-1;
                                    if(chatWithOtherSendNodeIds.size()>=3){
                                        position=1;
                                    }
                                    AccessibilityNodeInfo chatWithOtherSendNodeId=chatWithOtherSendNodeIds.get(position);
                                    clickXy(chatWithOtherSendNodeId);
                                    tikTokTask.showLogAndTsPrint("发送消息");
                                    Thread.sleep(2000);
                                    AccessibilityNodeInfo chatWithOtherFailTextNodeId = findNodeFirstById(FindIdResouresConfig.otherChatBottomSendFailTextId);
                                    if (chatWithOtherFailTextNodeId == null) {
                                        LogUtils.i("消息发送成功了");
                                    } else {
                                        LogUtils.i("消息发送失败了");
                                    }
                                    List<AccessibilityNodeInfo> listItemNodes = findNodesById(FindIdResouresConfig.newFanListItemNodeId);
                                    int backTimes = 0;
                                    while (!isNodeExist(listItemNodes)) {
                                        backTimes++;
                                        backOnce();
                                        Thread.sleep(2000);
                                        listItemNodes = findNodesById(FindIdResouresConfig.newFanListItemNodeId);
                                        if (backTimes >= 4) {
                                            return false;
                                        }
                                    }
                                    Thread.sleep(2000);
                                } else {
                                    return false;
                                }
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }
                    isStepSuccess = true;
                    swipeYearScrollBarToBottom(1);
                }
            }
            return isStepSuccess;
        }
    }
